使用poi生成Excel表格

POI 依赖包

<!-- excel表格 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <!-- <version>RELEASE</version> -->
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <!-- <version>RELEASE</version> -->
    <version>4.1.2</version>
</dependency>

生成表格工具类

生成表格的实体类放在最下面了

package com.pro.demo.utils;

import com.pro.demo.vo.ReportedExcelDataVo;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Excel 表格生成工具类
 */
public class ExcelUtil {

    private static final String PATH = "C:\\Users\\Lenovo\\Desktop\\temp\\poi";

    public static void main(String[] args) {
        ReportedExcelDataVo dataObject = new ReportedExcelDataVo();
        dataObject.setTitle("xxx评估表");
        dataObject.setFillUnit("广东省xxx办事处");
        dataObject.setFillUser("张珊珊");
        dataObject.setSealTime(new Date());

        ReportedExcelDataVo.ReportedSubjectDataVo infoList1 = new ReportedExcelDataVo.ReportedSubjectDataVo();
        infoList1.setSubjectName("基本信息");
        ArrayList<Map<String, Map<String, String>>> list = new ArrayList<>();
        Map<String, Map<String, String>> map = new LinkedHashMap<>();
        map.put("name", createMap("填报单位", "广东省xxx办事处"));
        map.put("age", createMap("填报人", "张珊珊"));
        map.put("sex", createMap("填报日期", "2022-05-12"));
        list.add(map);
        infoList1.setSubjectDataItem(list);

        ReportedExcelDataVo.ReportedSubjectDataVo infoList2 = new ReportedExcelDataVo.ReportedSubjectDataVo();
        infoList2.setSubjectName("详细记录");
        ArrayList<Map<String, Map<String, String>>> list2 = new ArrayList<>();
        Map<String, Map<String, String>> map2 = new LinkedHashMap<>();
        map2.put("name", createMap("实施清单", "上访案件"));
        map2.put("age", createMap("当月数量", "18"));
        map2.put("sex", createMap("当月解决", "25"));
        Map<String, Map<String, String>> map3 = new LinkedHashMap<>();
        map3.put("name", createMap("实施清单", "消防巡检"));
        map3.put("age", createMap("当月数量", "100"));
        map3.put("sex", createMap("当月解决", "25"));
        list2.add(map2);
        list2.add(map3);
        infoList2.setSubjectDataItem(list2);

        dataObject.setSubjectData(Arrays.asList(infoList1, infoList2));

        createWorkbookExcel(dataObject);
    }

    /**
     * 创建上报 Excel 表格
     *
     * @param dataObject
     */
    public static void createWorkbookExcel(ReportedExcelDataVo dataObject) {
        Workbook wb = new HSSFWorkbook();
        int rowSize = 0;

        // 创建工作表1
        Sheet sheet = wb.createSheet();

        // 合并单元格, CellRangeAddress 四个参数为:起始行,结束行,起始列,结束列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1)); // 合并第一行的1、2列
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 1)); // 合并第二行的1、2列
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 1)); // 合并第三行的1、2列

        // 设置某一列的宽度(列, 宽度), 列宽的字符是 1/256, 所以 *256
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 30 * 256);

        // 分隔行数
        int separatorRows = 2;

        // 创建右上角第一行
        Row topRow = sheet.createRow(rowSize);
        // 设置行高, 行高像素点是1/20, 所以 *20
        topRow.setHeight((short) (40 * 20));
        Cell topRightCell = topRow.createCell(0);
        topRightCell.setCellValue("TBPC_20220520");
        // 创建样式
        CellStyle topRightCellStyle = wb.createCellStyle();
        topRightCellStyle.setVerticalAlignment(VerticalAlignment.TOP); // 垂直对齐方式
        topRightCellStyle.setAlignment(HorizontalAlignment.RIGHT); // 水平对齐方式
        // 填充样式
        topRightCell.setCellStyle(topRightCellStyle);

        // 创建第1行
        rowSize += 1;
        Row row1 = sheet.createRow(rowSize);
        // 设置当前行的高度, 行高像素点是1/20, 所以 *20
        row1.setHeight((short) (40 * 20)); // 行高 *20
        // 给列赋值
        Cell cell = row1.createCell(0);
        cell.setCellValue(dataObject.getTitle());
        // 创建样式
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直对齐方式
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平对齐方式
        // 创建字体
        Font font = wb.createFont();
        font.setFontHeight((short) (15 * 20)); // 字体大小 *20
        font.setBold(true); // 字体加粗
        cellStyle.setFont(font);
        // 填充样式
        cell.setCellStyle(cellStyle);

        // 创建第2行
        rowSize += 1;
        Row row2 = sheet.createRow(rowSize);
        // 设置当前行的高度, 行高像素点是1/20, 所以 *20
        row2.setHeight((short) (40 * 20)); // 行高 *20
        // 设置样式
        CellStyle cellStyle2 = wb.createCellStyle();
        // 设置对齐方式
        cellStyle2.setVerticalAlignment(VerticalAlignment.TOP); // 垂直对齐方式
        cellStyle2.setAlignment(HorizontalAlignment.CENTER); // 水平对齐方式
        // 创建字体
        Font subjectTitleFont = wb.createFont();
        subjectTitleFont.setFontHeight((short) (12 * 20));
        cellStyle2.setFont(subjectTitleFont);
        // 给列赋值
        Cell cell1 = row2.createCell(0);
        cell1.setCellValue("电子签章文件");
        cell1.setCellStyle(cellStyle2);

        // 创建第3行
        rowSize += separatorRows;
        Row row3 = sheet.createRow(rowSize);
        row3.createCell(0).setCellValue("填报单位:");
        row3.createCell(1).setCellValue(dataObject.getFillUnit());

        // 创建第4行
        rowSize += separatorRows;
        Row row4 = sheet.createRow(rowSize);
        row4.createCell(0).setCellValue("填报人:");
        row4.createCell(1).setCellValue(dataObject.getFillUser());

        // 创建第5行
        rowSize += separatorRows;
        Row row5 = sheet.createRow(rowSize);
        row5.createCell(0).setCellValue("申请时间:");
        row5.createCell(1).setCellValue(DateFormatUtils.format(dataObject.getSealTime(), "yyyy-MM-dd HH:mm:ss"));

        // 创建第6行
        rowSize += separatorRows + 3;
        Row row6 = sheet.createRow(rowSize);
        row6.createCell(0).setCellValue("签章:");

        CellStyle contentStyle = wb.createCellStyle();
        contentStyle.setWrapText(true); // 自动换行
        contentStyle.setVerticalAlignment(VerticalAlignment.TOP); // 垂直对齐方式
        contentStyle.setAlignment(HorizontalAlignment.LEFT); // 水平对齐方式


        // 创建工作表2
        createReportedContentSheet(wb, dataObject);

        // 生成文件
        OutputStream outputStream = null;
        try {
            String fileName = String.format("%s/poi生成表格_%s.xls", PATH, System.currentTimeMillis());
            outputStream = new FileOutputStream(fileName);
            wb.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (Exception e) {

            }
            try {
                if (wb != null) {
                    wb.close();
                }
            } catch (Exception e) {

            }
        }
    }

    /**
     * 生成上报工作表
     *
     * @param wb
     * @param dataObject
     */
    private static void createReportedContentSheet(Workbook wb, ReportedExcelDataVo dataObject) {
        int rowSize = 0;
        // 分隔行数
        int separatorRows = 2;

        // 创建工作表1
        Sheet sheet = wb.createSheet();

        // 合并单元格, CellRangeAddress 四个参数为:起始行,结束行,起始列,结束列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1)); // 合并第一行的1、2列
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 1)); // 合并第二行的1、2列

        // 设置某一列的宽度(列, 宽度), 列宽的字符是 1/256, 所以 *256
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 30 * 256);

        // 创建右上角第一行
        Row topRow = sheet.createRow(rowSize);
        // 设置行高, 行高像素点是1/20, 所以 *20
        topRow.setHeight((short) (40 * 20));
        Cell topRightCell = topRow.createCell(0);
        topRightCell.setCellValue("附录内容");
        // 创建样式
        CellStyle topRightCellStyle = wb.createCellStyle();
        topRightCellStyle.setVerticalAlignment(VerticalAlignment.TOP); // 垂直对齐方式
        topRightCellStyle.setAlignment(HorizontalAlignment.RIGHT); // 水平对齐方式
        // 填充样式
        topRightCell.setCellStyle(topRightCellStyle);

        // 创建第1行
        rowSize += 1;
        Row row1 = sheet.createRow(rowSize);
        // 设置当前行的高度, 行高像素点是1/20, 所以 *20
        row1.setHeight((short) (40 * 20)); // 行高 *20
        // 给列赋值
        Cell cell = row1.createCell(0);
        cell.setCellValue(dataObject.getTitle());
        // 创建样式
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直对齐方式
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平对齐方式
        // 创建字体
        Font font = wb.createFont();
        font.setFontHeight((short) (15 * 20)); // 字体大小 *20
        font.setBold(true); // 字体加粗
        cellStyle.setFont(font);
        // 填充样式
        cell.setCellStyle(cellStyle);

        // 创建主题标题样式
        CellStyle subjectTitleStyle = wb.createCellStyle();
        Font subjectTitleFont = wb.createFont();
        subjectTitleFont.setFontHeight((short) (12 * 20));
        subjectTitleStyle.setFont(subjectTitleFont);

        // 填充主题数据
        List<ReportedExcelDataVo.ReportedSubjectDataVo> subjectList = dataObject.getSubjectData();
        for (ReportedExcelDataVo.ReportedSubjectDataVo subjectData : subjectList) {
            // 创建标题行
            rowSize += separatorRows;
            Row titleRow = sheet.createRow(rowSize);
            // 给列填充内容
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellValue(subjectData.getSubjectName());
            titleCell.setCellStyle(subjectTitleStyle);

            for (Map<String, Map<String, String>> stringMapMap : subjectData.getSubjectDataItem()) {
                for (Map.Entry<String, Map<String, String>> stringMapEntry : stringMapMap.entrySet()) {
                    Map<String, String> body = stringMapEntry.getValue();
                    // 创建内容行
                    rowSize += 1;
                    Row contentRow = sheet.createRow(rowSize);
                    contentRow.createCell(0).setCellValue(String.format("%s:", body.get("key")));
                    contentRow.createCell(1).setCellValue(body.get("value"));
                    // 设置当前行的高度, 行高像素点是1/20, 所以 *20
                    contentRow.setHeight((short) (18 * 20)); // 行高 *20
                }
                // 每个主题行下面的主题列表结束之后隔开一行
                rowSize += 1;
            }
        }
    }

    public static Map<String, String> createMap(String key, String value) {
        Map<String, String> map = new HashMap<>(2);
        map.put("key", key);
        map.put("value", value);
        return map;
    }
}


生成表格实体

package com.pro.demo.vo;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 上报生成Excel对象
 */
public class ReportedExcelDataVo implements Serializable {

    /**
     * 表格标题
     */
    private String title;

    /**
     * 填报单位
     */
    private String fillUnit;

    /**
     * 填报人
     */
    private String fillUser;

    /**
     * 签章时间
     */
    private Date sealTime;

    /**
     * 填报主题数据
     */
    private List<ReportedSubjectDataVo> subjectData;


    /**
     * 主题数据对象
     */
    public static class ReportedSubjectDataVo implements Serializable {

        /**
         * 主题名称
         */
        private String subjectName;

        /**
         * 主题数据项
         * [
         *  { "数据项key1": { key: "数据项名称", value: "数据项值" } },
         *  { "数据项key2": { key: "数据项名称", value: "数据项值" } }
         * ]
         */
        private List<Map<String, Map<String, String>>> subjectDataItem;
    }

	// 此次省略get、set
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供帮助。首先,您需要在您的项目中添加 POIPOI-OOXML 依赖。您可以在您的 pom.xml 文件中添加以下依赖: ```xml <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> ``` 接下来,您可以创建一个类来生成 Excel 文件。以下是一个简单的示例: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; public class ExcelExporter { public static void export() throws IOException { // 创建一个工作簿 Workbook workbook = new XSSFWorkbook(); // 创建一个工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 创建一个行 Row row = sheet.createRow(0); // 创建单元格并添加值 Cell cell = row.createCell(0); cell.setCellValue("Hello World"); // 保存工作簿 FileOutputStream outputStream = new FileOutputStream("output.xlsx"); workbook.write(outputStream); workbook.close(); } } ``` 在这个例子中,我们创建了一个工作簿,然后创建了一个工作表和一行。我们然后创建了一个单元格,将值设置为 "Hello World"。最后,我们将工作簿保存到文件中。 您可以通过调用 `ExcelExporter.export()` 来生成 Excel 文件。这将在项目的根目录下创建一个名为 "output.xlsx" 的文件。 当然,这只是一个简单的示例。如果您需要更复杂的 Excel 文件,您可以使用 POI 的其他功能来添加样式、合并单元格等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值