• Apache POI处理Miscrosoft Office 各种文件格式的开源项目


    介绍:

    应用场景

    maven 坐标

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

    方法及其作用

            创建/写入

    1. //创建Excel文件 并且写入文件内容(在内存中创建)
    2. XSSFWorkbook excel = new XSSFWorkbook();

    XSSFWorkbook()创建的excel表默认没有sheet页 需要手动创建

    XSSFSheet sheet = excel.createSheet();//创建一个sheet页
     
    
    1. XSSFWorkbook excel = new XSSFWorkbook();//新建excel表
    2. XSSFSheet sheet = excel.createSheet("info");//创建一个sheet页
    3. //输入sheet名字
    4. XSSFRow row = sheet.createRow(1);//创建第二行(从0开始)
    5. row.createCell(1).setCellValue("姓名");//创建单元格也是从0开始 这里表示创建第二个单元格
    6. //在单元格中写入内容
    7. row.createCell(2).setCellValue("年龄");
    8. XSSFRow row1 = sheet.createRow(2);
    9. row1.createCell(1).setCellValue("小李");
    10. row1.createCell(2).setCellValue("18");

    通过excel在磁盘创建

    1. //通过输出流将excel写入磁盘
    2. FileOutputStream info = new FileOutputStream(new File("D://info.xlsx"));
    3. excel.write(info);
    4. info.close();
    5. excel.close();//关闭资源

    执行之后

            读取

    1. //通过输入流获取表格
    2. FileInputStream in = new FileInputStream(new File("D://info.xlsx"));
    3. XSSFWorkbook excel = new XSSFWorkbook(in);//接收表格
    4. XSSFSheet sheet = excel.getSheetAt(0);//通过索引获取sheet页
    5. //XSSFSheet sheet1 = excel.getSheet("sheet");//通过名字获取sheet页
    6. int lastRowNum = sheet.getLastRowNum();//获取表中有内容的 最后一行的行号
    7. for (int i = 1; i <= lastRowNum; i++) {
    8. //已知有内容的最后一行 循环读取sheet页中内容
    9. XSSFRow row = sheet.getRow(i);
    10. XSSFCell cell = row.getCell(1);
    11. XSSFCell cell1 = row.getCell(2);
    12. System.out.println(cell + " " + cell1);
    13. }
    14. in.close();
    15. excel.close();

    执行结果 记得关流 

  • 相关阅读:
    <C++> list模拟实现
    天龙八部科举答题问题和答案(全3/8)
    python基础-面向对象
    SSM整合
    uniapp云打包app使用sqlite实现本地缓存,以及云打包sqlite不生效踩坑记录
    三十九、Fluent时间步长的估算与库朗数
    worthington丨worthington用于细胞收获的胰蛋白酶
    为什么我从 Swift 转向 Flutter,你也应该这样做
    Elasticsearch 集群时的内部结构是怎样的?
    湖仓一体架构的特性
  • 原文地址:https://blog.csdn.net/2301_79106424/article/details/136454197