JAVA POI导出复杂表头Excel(纯java代码)

Excel表格示例:

                                                                                                     excel导出
 填表单位:测试单位                                                             2018年第3季度
             名称                                 人数情况              登记情况       备注
    登记数(人)   办证总数(人)   办证率(%)    登记户数(户)    签订数(份)
        测试名称1       2488         1452        60%        2450        2450备注1
        测试名称2     备注2
              合计        2488         1452         2450        2450 
   注:POI导出复杂表头Excel(纯java代码)
   审核人:张三   填表人:李四   填表时间:2018-10-29

Java代码如下:

response.setContentType("application/vnd.ms-excel");
// 文件名
String fileName = "报表名称.xls";
// 特殊编码转译
fileName = StringUtils.charConversion(fileName);
// 处理文件名包含特殊字符出现的乱码问题
String userAgent = request.getHeader("User-Agent");
if (StringUtils.isNotBlank(userAgent)) {
    userAgent = userAgent.toLowerCase();
    if (userAgent.contains("msie") || userAgent.contains("trident") || userAgent.contains("edge")) {
        if (fileName.length() > 150) {// 解决IE 6.0问题
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        } else {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }
    } else {
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
    }
}
response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
OutputStream stream = response.getOutputStream();
// 创建excel文件对象
HSSFWorkbook wb = new HSSFWorkbook();
// 创建sheet
Sheet sheet = wb.createSheet("sheet1");
//表头字体
Font headerFont = wb.createFont();
headerFont.setFontName("微软雅黑");
headerFont.setFontHeightInPoints((short) 18);
headerFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
headerFont.setColor(HSSFColor.BLACK.index);
//正文字体
Font contextFont = wb.createFont();
contextFont.setFontName("微软雅黑");
contextFont.setFontHeightInPoints((short) 12);
contextFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
contextFont.setColor(HSSFColor.BLACK.index);

//表头样式,左右上下居中
CellStyle headerStyle = wb.createCellStyle();
headerStyle.setFont(headerFont);
headerStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
headerStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
headerStyle.setLocked(true);
headerStyle.setWrapText(false);// 自动换行
//单元格样式,左右上下居中 边框
CellStyle commonStyle = wb.createCellStyle();
commonStyle.setFont(contextFont);
commonStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
commonStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
commonStyle.setLocked(true);
commonStyle.setWrapText(false);// 自动换行
commonStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
commonStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
commonStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
commonStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
//单元格样式,左右上下居中 边框
CellStyle commonWrapStyle = wb.createCellStyle();
commonWrapStyle.setFont(contextFont);
commonWrapStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
commonWrapStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
commonWrapStyle.setLocked(true);
commonWrapStyle.setWrapText(true);// 自动换行
commonWrapStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
commonWrapStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
commonWrapStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
commonWrapStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
//单元格样式,竖向 边框
CellStyle verticalStyle = wb.createCellStyle();
verticalStyle.setFont(contextFont);
verticalStyle.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
verticalStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
verticalStyle.setRotation((short) 255);//竖向
verticalStyle.setLocked(true);
verticalStyle.setWrapText(false);// 自动换行
verticalStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
verticalStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
verticalStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
verticalStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

//单元格样式,左右上下居中 无边框
CellStyle commonStyleNoBorder = wb.createCellStyle();
commonStyleNoBorder.setFont(contextFont);
commonStyleNoBorder.setAlignment(CellStyle.ALIGN_CENTER);// 左右居中
commonStyleNoBorder.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
commonStyleNoBorder.setLocked(true);
commonStyleNoBorder.setWrapText(false);// 自动换行
//单元格样式,左对齐 边框
CellStyle alignLeftStyle = wb.createCellStyle();
alignLeftStyle.setFont(contextFont);
alignLeftStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
alignLeftStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
alignLeftStyle.setLocked(true);
alignLeftStyle.setWrapText(false);// 自动换行
alignLeftStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
alignLeftStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
alignLeftStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
alignLeftStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
alignLeftStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
//单元格样式,左对齐 无边框
CellStyle alignLeftNoBorderStyle = wb.createCellStyle();
alignLeftNoBorderStyle.setFont(contextFont);
alignLeftNoBorderStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
alignLeftNoBorderStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
alignLeftNoBorderStyle.setLocked(true);
alignLeftNoBorderStyle.setWrapText(false);// 自动换行
alignLeftNoBorderStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
//单元格样式,右对齐
CellStyle alignRightStyle = wb.createCellStyle();
alignRightStyle.setFont(contextFont);
alignRightStyle.setAlignment(CellStyle.ALIGN_LEFT);// 左对齐
alignRightStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
alignRightStyle.setLocked(true);
alignRightStyle.setWrapText(false);// 自动换行
alignRightStyle.setAlignment(CellStyle.ALIGN_RIGHT);// 左对齐

// 填报时间
String tbsj = StringUtils.isBlank(dto.getTbsj()) ? "" : dto.getTbsj();
// 填报单位
String tbdwTxt = StringUtils.isBlank(dto.getTbdwTxt()) ? "" : dto.getTbdwTxt();
// 填报人
String cjrxm = StringUtils.isBlank(dto.getCjrxm()) ? "" : dto.getCjrxm();
// 审核人
String shrxm = StringUtils.isBlank(dto.getShrxm()) ? "" : dto.getShrxm();
// 年度 季度
String nd = StringUtils.isBlank(dto.getNd()) ? "" : dto.getNd();
String jd = StringUtils.isBlank(dto.getJd()) ? "" : dto.getJd();

// 行号
int rowNum = 0;
//设置列宽
for (int i = 0; i < 7; i++) {
    sheet.setColumnWidth(i, 6000);
}

//第一行
Row r0 = sheet.createRow(rowNum++);
r0.setHeight((short) 800);
Cell c00 = r0.createCell(0);
c00.setCellValue(dto.getBbmc());
c00.setCellStyle(headerStyle);
//合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));

// 第二行
Row r1 = sheet.createRow(rowNum++);
r1.setHeight((short) 500);
String[] row_first = {"填表单位:", "", "", "", "", " 年第 季度:", ""};
for (int i = 0; i < row_first.length; i++) {
    Cell tempCell = r1.createCell(i);
    tempCell.setCellStyle(alignLeftNoBorderStyle);
    if (i == 0) {
        tempCell.setCellValue(row_first[i] + tbdwTxt);
    } else if (i == 5) {
        tempCell.setCellStyle(alignRightStyle);
        if (StringUtils.isNotBlank(nd) && StringUtils.isNotBlank(jd))
            tempCell.setCellValue(nd + "年第" + jd + "季度");
        else
            tempCell.setCellValue(row_first[i]);
    } else {
        tempCell.setCellValue(row_first[i]);
    }
}
// 合并
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 4));
sheet.addMergedRegion(new CellRangeAddress(1, 1, 5, 6));

//第三行
Row r2 = sheet.createRow(rowNum++);
r2.setHeight((short) 700);
String[] row_second = {"名称", "采集情况", "", "", "登记情况", "", "备注"};
for (int i = 0; i < row_second.length; i++) {
    Cell tempCell = r2.createCell(i);
    tempCell.setCellValue(row_second[i]);
    tempCell.setCellStyle(commonStyle);
}
// 合并
sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0));
sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 3));
sheet.addMergedRegion(new CellRangeAddress(2, 2, 4, 5));
sheet.addMergedRegion(new CellRangeAddress(2, 3, 6, 6));

//第三行
Row r3 = sheet.createRow(rowNum++);
r3.setHeight((short) 700);
String[] row_third = {"", "登记数(人)", "办证总数(人)", "办证率(%)", "登记户数(户)", "签订数(份)", ""};
for (int i = 0; i < row_third.length; i++) {
    Cell tempCell = r3.createCell(i);
    tempCell.setCellValue(row_third[i]);
    tempCell.setCellStyle(commonWrapStyle);
}

//循环每一行
for (FluidPopulationInfoGatherReportDto excelData : list) {
    Row tempRow = sheet.createRow(rowNum++);
    tempRow.setHeight((short) 500);
    // 循环单元格填入数据
    for (int j = 0; j < 7; j++) {
        Cell tempCell = tempRow.createCell(j);
        tempCell.setCellStyle(commonStyle);
        String tempValue;
        if (j == 0) {
            // 乡镇、街道名称
            tempValue = excelData.getTbdwTxt();
        } else if (j == 1) {
            // 登记数(人)
            tempValue = excelData.getLdrkdjs();
        } else if (j == 2) {
            // 办证总数(人)
            tempValue = excelData.getJzzbzzs();
        } else if (j == 3) {
            // 办证率(%)
            tempValue = StringUtils.isNotBlank(excelData.getJzzbzl()) ? excelData.getJzzbzl() + "%" : "";
        } else if (j == 4) {
            // 登记户数(户)
            tempValue = excelData.getCzfwdjhs();
        } else if (j == 5) {
            // 签订数(份)
            tempValue = excelData.getZazrsqds();
        } else {
            // 备注
            tempValue = excelData.getRemark();
        }
        tempCell.setCellValue(tempValue);
    }
}

// 注释行
Row remark = sheet.createRow(rowNum++);
remark.setHeight((short) 500);
String[] row_remark = {"注:表中的“办证率=办证总数÷登记数×100%”", "", "", "", "", "", ""};
for (int i = 0; i < row_remark.length; i++) {
    Cell tempCell = remark.createCell(i);
    if (i == 0) {
        tempCell.setCellStyle(alignLeftStyle);
    } else {
        tempCell.setCellStyle(commonStyle);
    }
    tempCell.setCellValue(row_remark[i]);
}
int remarkRowNum = list.size() + 4;
// 注
sheet.addMergedRegion(new CellRangeAddress(remarkRowNum, remarkRowNum, 0, 6));

// 尾行
Row foot = sheet.createRow(rowNum++);
foot.setHeight((short) 500);
String[] row_foot = {"审核人:", "", "填表人:", "", "填表时间:", "", ""};
for (int i = 0; i < row_foot.length; i++) {
    Cell tempCell = foot.createCell(i);
    tempCell.setCellStyle(alignLeftNoBorderStyle);
    if (i == 0) {
        tempCell.setCellValue(row_foot[i] + shrxm);
    } else if (i == 2) {
        tempCell.setCellValue(row_foot[i] + cjrxm);
    } else if (i == 4) {
        tempCell.setCellValue(row_foot[i] + tbsj);
    } else {
        tempCell.setCellValue(row_foot[i]);
    }
}
int footRowNum = list.size() + 5;
// 注
sheet.addMergedRegion(new CellRangeAddress(footRowNum, footRowNum, 0, 1));
sheet.addMergedRegion(new CellRangeAddress(footRowNum, footRowNum, 2, 3));
sheet.addMergedRegion(new CellRangeAddress(footRowNum, footRowNum, 4, 6));

//导出
try {
   if (null != wb && null != stream) {
      wb.write(out);
      out.close();
   }
} catch (Exception e) {
   logger.error("excel文档导出错误-异常信息:", e);
}

 

  • 8
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
你可以使用Apache POI库来导出动态表头Excel文件。首先,你需要创建一个Workbook对象,然后创建一个Sheet对象。接下来,你可以使用Row和Cell对象创建行和单元格,并设置相应的值。 下面是一个示例代码,演示如何使用Apache POI导出具有动态表头Excel文件: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; public class ExcelExporter { public static void main(String[] args) { List<String> headers = Arrays.asList("Header 1", "Header 2", "Header 3"); // 动态表头 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 创建表头行 Row headerRow = sheet.createRow(0); for (int i = 0; i < headers.size(); i++) { Cell headerCell = headerRow.createCell(i); headerCell.setCellValue(headers.get(i)); } // 创建数据行 // 假设有两行数据 List<List<String>> data = Arrays.asList( Arrays.asList("Data 1", "Data 2", "Data 3"), Arrays.asList("Data 4", "Data 5", "Data 6") ); int rowIndex = 1; // 数据行索引从1开始 for (List<String> rowData : data) { Row dataRow = sheet.createRow(rowIndex++); for (int i = 0; i < rowData.size(); i++) { Cell dataCell = dataRow.createCell(i); dataCell.setCellValue(rowData.get(i)); } } // 保存Excel文件 try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) { workbook.write(outputStream); System.out.println("Excel导出成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们使用了XSSFWorkbook类来创建一个Excel文件,并创建了一个名为"Sheet1"的工作表。然后,我们根据动态表头创建了表头行,并使用循环创建了数据行。最后,我们将工作簿写入输出流,并保存为名为"output.xlsx"的文件。 你可以根据自己的需求修改表头和数据,然后使用上述代码导出具有动态表头Excel文件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值