• Java导出数据到Excel


    Java 导出数据到Excel

    XSSFWorkbook wb = new XSSFWorkbook();
    第1步、构建Workbook 数据
    buildData(wb, persons);
    第2步、设置Workbook 格式
    buildStyle(wb);
    第3步、导出到Excel
    writeExcel(wb);

    第1步、构建Workbook 数据

    public static void buildData(Workbook wb, List<Person> list) {
        // 创建sheet页
        Sheet sheetName = wb.createSheet("sheetName");
        
        // 填充表头
        Row row = sheetName.createRow(0);
        row.createCell(0).setCellValue("Id");
        row.createCell(1).setCellValue("Name");
        row.createCell(2).setCellValue("Age");
        row.createCell(3).setCellValue("NickName");
        
        // 填充内容
        for (int i = 0; i < list.size(); i++) {
            Person person = list.get(i);
            row = sheetName.createRow(i + 1);
            row.createCell(0).setCellValue(person.getId());
            row.createCell(1).setCellValue(person.getName());
            row.createCell(2).setCellValue(person.getAge());
            row.createCell(3).setCellValue(person.getNickName());
        }
        
        // sheet页重命名
        wb.setSheetName(0, "sheet");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    第2步、设置Workbook 格式

    public static void buildStyle(Workbook wb) {
        Sheet sheet;
        Row row;
        for (int s = 0; s < wb.getNumberOfSheets(); s++) { // 遍历Sheet页
            sheet = wb.getSheetAt(s);
            for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) { // 遍历所有行
                row = sheet.getRow(r);
                for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) { // 遍历每一样所有单元格
                    if (r == 0) { // 表头
                        row.getCell(c).setCellStyle(ExcelStyleUtils.headerStyle(wb)); // 设置格式
                        sheet.autoSizeColumn(c); // 列自动伸缩
                    } else { // 数据
                        row.getCell(c).setCellStyle(ExcelStyleUtils.cellsStyle(wb)); // 设置格式
                        if (sheet.getColumnWidth(c) > 50 * 256) {
                            sheet.setColumnWidth(c, 50 * 256); // 设置列宽
                        }
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    第3步、导出到Excel

    # FileOutputStream
    public static void writeExcel(Workbook workbook) throws Exception {
        FileIUtils.deleteDirAndFiles(OUT_PATH);
        FileIUtils.makeSureDirExist(OUT_PATH);
        
        String exportPath = FileIUtils.genFileName(OUT_PATH, "文件名", ".xlsx");
        try (FileOutputStream fos = new FileOutputStream(exportPath, false)) {
            workbook.write(fos);
        }
    }
    
    # OutputStream 
    public static void writeExcel2(Workbook workbook) throws Exception {
        FileIUtils.deleteDirAndFiles(OUT_PATH);
        FileIUtils.makeSureDirExist(OUT_PATH);
        
        String exportPath = FileIUtils.genFileName(OUT_PATH, "文件名", ".xlsx");
        try (OutputStream outputStream = new FileOutputStream(exportPath)) {
            workbook.write(outputStream);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    Further Reading : FileIUtils 共通方法最佳实践

    测试

    @Test
    public void testWriteExcel2() throws Exception {
        List<Person> persons = new ArrayList<>();
        persons.add(new Person(10, "John", 11, "nickName"));
        persons.add(new Person(11, "John1", 11, "nickName1"));
        persons.add(new Person(12, "John2", 11, "nickName2"));
        persons.add(new Person(13, "John3", 11, "nickName3"));
        persons.add(new Person(14, "John4", 11, "nickName4"));
        
        XSSFWorkbook wb = new XSSFWorkbook();
        buildData(wb, persons); // 构建数据
        
        buildStyle(wb); // 设置格式
        
    	writeExcel(wb);writeExcel2(wb); // 导出数据
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    结果展示
    在这里插入图片描述


    核心import

    import model.Person;
    import org.apache.commons.io.FileUtils;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import java.io.*;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    maven 依赖

    
    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poiartifactId>
        <version>5.2.3version>
    dependency>
    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poi-ooxmlartifactId>
        <version>5.2.3version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    拓展

    Java读取excel中的数据
    Java导出数据到Excel
    Java给Excel设置单元格格式

  • 相关阅读:
    【C++入门】命名空间&缺省参数&函数重载&引用
    12.(vue3.x+vite)组件间通信方式之$attrs与$listeners
    【博客498】k8s kubelet device-plugins
    康耐视visionpro定位引导标定简介及方法
    JSR303参数校验
    活字格性能优化技巧(1)——如何利用数据库主键提升访问性能
    C#串口通信从入门到精通(25)——整数/小数(浮点数)和字节数组互相转换
    XStream反序列化
    day15--使用postman, newman和jenkins进行接口自动化测试
    再扩国产化信创版图!朗思科技与中科方德完成产品兼容性互认证
  • 原文地址:https://blog.csdn.net/weixin_37646636/article/details/132039605