• Apache POC(对Excel文件操作)


    介绍

    Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目,我们可以使用POI在java程序中对Miscrosoft Office各种文件进行读写操作

    一般情况下,POI都是用于操作Excel文件。

    Apache POI的maven坐标:

    1. <!-- poi -->
    2. <dependency>
    3. <groupId>org.apache.poi</groupId>
    4. <artifactId>poi</artifactId>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.apache.poi</groupId>
    8. <artifactId>poi-ooxml</artifactId>
    9. </dependency>

    Test写入测试

    1. package com.sky.test;
    2. import org.apache.poi.xssf.usermodel.XSSFRow;
    3. import org.apache.poi.xssf.usermodel.XSSFSheet;
    4. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    5. import java.io.FileOutputStream;
    6. /**
    7. * @author Mtz
    8. * @version 1.0
    9. * @2023/9/2214:33
    10. * @function
    11. * @comment
    12. */
    13. public class POITest {
    14. public static void write() throws Exception {
    15. // 在内存中创建一个Excel文件
    16. XSSFWorkbook excel = new XSSFWorkbook();
    17. // 在Excel文件中创建一个Sheet页
    18. XSSFSheet sheet = excel.createSheet("info");
    19. // 在Sheet中创建行对象,rownum编号从0开始
    20. XSSFRow row = sheet.createRow(0);
    21. // 在创建单元格并且写入文件内容
    22. row.createCell(1).setCellValue("城市");
    23. row.createCell(2).setCellValue("姓名");
    24. row = sheet.createRow(1);
    25. row.createCell(1).setCellValue("北京");
    26. row.createCell(2).setCellValue("张三");
    27. row = sheet.createRow(2);
    28. row.createCell(1).setCellValue("北京");
    29. row.createCell(2).setCellValue("张三");
    30. FileOutputStream out = new FileOutputStream(("D:\\info.xlsx"));
    31. excel.write(out);
    32. // 关闭资源
    33. out.close();
    34. excel.close();
    35. }
    36. public static void main(String[] args) throws Exception {
    37. write();
    38. }
    39. }

    Test读取测试

    1. public static void read() throws Exception{
    2. FileInputStream in = new FileInputStream("D:\\info.xlsx");
    3. XSSFWorkbook excel = new XSSFWorkbook(in);
    4. // 读取Excel文件中的第一个sheet页
    5. XSSFSheet sheetAt = excel.getSheetAt(0);
    6. // 获取Sheet中最后一行的行号
    7. int lastRowNum = sheetAt.getLastRowNum();
    8. for (int i = 1; i <= lastRowNum; i++) {
    9. XSSFRow row = sheetAt.getRow(i);
    10. String stringCellValue = row.getCell(1).getStringCellValue();
    11. String stringCellValue2 = row.getCell(1).getStringCellValue();
    12. System.out.println(stringCellValue+" "+stringCellValue2);
    13. }
    14. in.close();
    15. excel.close();
    16. }

  • 相关阅读:
    kafka各版本消息介绍
    Java基础访问权限控制符
    【模电实验】【超值1 + 1】【验证性实验——分立元件“OTL“功率放大器实验】【验证性实验——分立元件稳压电源实验】
    Golang——从入门到放弃
    分布式缓存
    【Vue面试题十一】、Vue组件之间的通信方式都有哪些?
    聚乙二醇衍生物4-Arm PEG-DSPE,四臂-聚乙二醇-磷脂
    python+playwright 学习-82 Request 对象
    【洛谷 P5266】【深基17.例6】学籍管理 题解(映射+分支)
    【SpringBoot】SpringBoot中使用JPA进行数据库操作
  • 原文地址:https://blog.csdn.net/weixin_67573348/article/details/133169276