使用POI实现操作Excel文件。

news/2024/7/21 4:13:28 标签: excel
1、添加依赖
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>4.1.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.1.2</version>
    </dependency>
2、xls和xlsx的区别介绍
  1. xls是Excel03版本,最大支持65536行、256列,poi 操作xls,使用HSSFWorkbook
  2. xlsx是Excel007版本,最大支持1048576行、16384列,poi-ooml操作xlsx,使用XSSFWorkbook

3、代码示例,读取Excel
/**
 * 读.xlsx文件
 */
private static List<List<String>> readXlsx(String path) throws Exception {
    InputStream is = Files.newInputStream(Paths.get(path));
    XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
    List<List<String>> result = new ArrayList<List<String>>();
    // 循环每一页,并处理当前循环页 (sheet 页)
    int numberOfSheets = xssfWorkbook.getNumberOfSheets();
    for (int i = 0; i < numberOfSheets; i++) {
        XSSFSheet sheetAt = xssfWorkbook.getSheetAt(i);
        if (sheetAt == null) {
            continue;
        }
        // 从第一行一直循环到当前sheet的最后一行
        for (int rowNum = 1; rowNum <= sheetAt.getLastRowNum(); rowNum++) {
            // 获取行数据,然后在获取列数据
            XSSFRow xssfRow = sheetAt.getRow(rowNum);
            int minColIx = xssfRow.getFirstCellNum();
            int maxColIx = xssfRow.getLastCellNum();
            List<String> rowList = new ArrayList<String>();
            for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                XSSFCell cell = xssfRow.getCell(colIx);
                if (cell == null) {
                    continue;
                }
                rowList.add(cell.toString());
            }
            result.add(rowList);
        }
    }
    return result;
}

/**
 * 读.xls文件
 */
private static List<List<String>> readXls(String path) throws IOException {
    InputStream is = Files.newInputStream(Paths.get(path));
    HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
    List<List<String>> result = new ArrayList<List<String>>();
    int numberOfSheets = hssfWorkbook.getNumberOfSheets();
    for (int i = 0; i < numberOfSheets; i++) {
        HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(i);
        if (hssfSheet == null) {
            continue;
        }
        int firstRowNum = hssfSheet.getFirstRowNum();
        int lastRowNum = hssfSheet.getLastRowNum();
        for (int rowIx = firstRowNum; rowIx < lastRowNum; rowIx++) {
            HSSFRow row = hssfSheet.getRow(rowIx);
            int minColIx = row.getFirstCellNum();
            int maxColIx = row.getLastCellNum();
            List<String> rowList = new ArrayList<String>();
            for (int colIx = minColIx; colIx < maxColIx; colIx++) {
                HSSFCell cell = row.getCell(colIx);
                if (cell == null) {
                    continue;
                }
                rowList.add(cell.toString());
            }
            result.add(rowList);
        }
    }
    return result;
}
4、代码示例,写Excel (HSSFWorkBook类似)
// 将上面读取的数据,在重新写到一个新的文件中
private static void writeXlsx(List<List<String>> dataList, String destPath) throws IOException {
    // 创建一个工作簿
    XSSFWorkbook xssfWorkbook = new XSSFWorkbook();

    Sheet sheet001 = xssfWorkbook.createSheet("sheet001");
    for (int i = 0; i < dataList.size(); i++) {
        Row row = sheet001.createRow(i);
        List<String> rowData = dataList.get(i);
        for (int j = 0; j < rowData.size(); j++) {
            Cell cell = row.createCell(j);
            cell.setCellValue(rowData.get(j));
        }
    }

    FileOutputStream fileOutputStream = new FileOutputStream(destPath);
    xssfWorkbook.write(fileOutputStream);
    fileOutputStream.close();
}

5、合并单元格 --- addMergedRegion
private static void mergeWithXSSF(String destPath) throws IOException {
    XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
    XSSFSheet sheet = xssfWorkbook.createSheet("new Sheet");
    XSSFRow row = sheet.createRow(1);
    XSSFCell cell = row.createCell(1);
    cell.setCellValue("测试合并单元格");
    // 按照范围合并单元格
    sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));

    FileOutputStream fileOutputStream = new FileOutputStream(destPath);
    xssfWorkbook.write(fileOutputStream);
    fileOutputStream.close();
}

合并效果:

6.合并单元格的优化 -----  addMergedRegionUnsafe

当我们还使用addMergedRegion方法的时候,比如循环10000次合并操作,可以计算一下耗时

private static void mergeWithXSSF1(String destPath) throws IOException {
    XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
    XSSFSheet sheet = xssfWorkbook.createSheet("new Sheet");

    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
        XSSFRow row = sheet.createRow(i);
        XSSFCell cell = row.createCell(1);
        cell.setCellValue("测试合并单元格");
        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));
    }
    long endTime = System.currentTimeMillis();
    System.out.println("耗费时间: " + (endTime - startTime));
    FileOutputStream fileOutputStream = new FileOutputStream(destPath);
    xssfWorkbook.write(fileOutputStream);
    fileOutputStream.close();
}

耗费时间: 22918

如果换成addMergedRegionUnsafe方法,同样循环10000次合并操作,计算了一下耗时

private static void mergeWithXSSF1(String destPath) throws IOException {
    XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
    XSSFSheet sheet = xssfWorkbook.createSheet("new Sheet");

    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 10000; i++) {
        XSSFRow row = sheet.createRow(i);
        XSSFCell cell = row.createCell(1);
        cell.setCellValue("测试合并单元格");
        // 改成不校验
        sheet.addMergedRegionUnsafe(new CellRangeAddress(i, i, 1, 2));
    }
    long endTime = System.currentTimeMillis();
    System.out.println("耗费时间: " + (endTime - startTime));
    FileOutputStream fileOutputStream = new FileOutputStream(destPath);
    xssfWorkbook.write(fileOutputStream);
    fileOutputStream.close();
}

耗费时间: 926

可以看到,消耗的时间是大大减少的。


http://www.niftyadmin.cn/n/5020255.html

相关文章

C高级day4(shell脚本)

一、Xmind整理&#xff1a; 二、上课笔记整理&#xff1a; 1.创建一个文件&#xff0c;给组用户可读权限&#xff0c;所属用户可写权限&#xff0c;其他用户可执行权限&#xff0c;使用if判断文件有哪些权限 #!/bin/bash touch 1 chmod 241 1 if [ -r 1 ] thenecho "文件…

File类操作

1. 练习一 在当前模块下的 text 文件夹中创建一个 io.txt 文件 import java.io.File; import java.io.IOException;public class Practice1 {public static void main(String[] args) {File file new File("D:\\kaifamiao");File file1 new File(file, "tex…

pyinstaller打包exe,使用wexpect的问题

参考github首先打包wexpect 1.进入wexpect目录执行 pyinstaller __main__.py -n wexpect 会生成dist文件夹 2.python代码A.py中使用wexpect&#xff0c;注意wexpect.spawn前后必须按照下面添加代码 import sys,os,wexpect #spawn前 real_executable sys.executable try:if sy…

MyBatisPlus 分页查询

首先要定义一个配置类 MybatisConfig 放在 config 类下 他的生效是通过拦截生效的 所以是要写拦截器的 (这段拦截器的配置是固定的 CV 也可以) Configuration public class MybatisConfig{Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){// 1.定义MybatisPlu…

stable diffusion实践操作-如何使用AI绘制动画

文章目录 大纲1.Temporal-Kit & Ebsynth动画制作流程1.安装2.图生图 参数设置1.提示词设置2.宽高设置1.seed 3.ControlNet 操作批量处理 4.批量处理统一的seed 2.真人视频转卡通动画4 .生成超稳定卡通动画 大纲 AI 绘图朝着动画和视频发展 本教程来源B站。 入口 1.Tempora…

基于小程序的理发店预约系统

一、项目背景及简介 现在很多的地方都在使用计算机开发的各种管理系统来提高工作的效率&#xff0c;给人们带来很多的方便。计算机技术从很大的程度上解放了人们的双手&#xff0c;并扩大了人们的活动范围&#xff0c;是人们足不出户就可以通过电脑进行各种事情的管理。信息系…

机器学习(8)---数据预处理

文章目录 一、数据预处理1.1 数据无量纲化1.2 数据归一化1.3 数据标准化1.4 处理选择 二、缺失值2.1 填补的类和参数2.2 用Pandas和Numpy进行填补 三、处理分类型特征&#xff1a;编码与哑变量3.1 编码3.2 哑变量&#xff08;独热编码&#xff09; 一、数据预处理 1.1 数据无量…

Pytorch intermediate(四) Language Model (RNN-LM)

前一篇中介绍了一种双向的递归神经网络&#xff0c;将数据进行正序输入和倒序输入&#xff0c;兼顾向前的语义以及向后的语义&#xff0c;从而达到更好的分类效果。 之前的两篇使用递归神经网络做的是分类&#xff0c;可以发现做分类时我们不需要使用时序输入过程中产生的输出&…