POI之EXCEL的export整理

本文详细介绍了一种使用Java批量导出数据到Excel的方法,包括文件路径设置、样式定义、表头生成、数据写入及文件输出等步骤,适用于大量数据的导出场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private String createImportExcel(List<DBObject> dataList , String entId, HttpServletRequest request) throws ServiceException {
// 设置文件名和文件路径
String fileName = "xxxxxxx";
String path = request.getSession().getServletContext().getRealPath("/") + "downloads/";
String fullPath = path + fileName;
File excelFile = new File(fullPath);
if(!excelFile.getParentFile().exists()){
     //如果目标文件所在的目录不存在,则创建父目录
     excelFile.getParentFile().mkdirs();
}
// 创建excel对象
Workbook wb = new SXSSFWorkbook(2000);
//设置excel样式
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
DataFormat df = wb.createDataFormat();
CellStyle style;
//样式一
Font headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
style = createBorderedStyle(wb);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFont(headerFont);
styles.put("header", style);
//样式二
style = createBorderedStyle(wb);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFont(headerFont);
style.setDataFormat(df.getFormat("d-mmm"));
styles.put("header_date", style);
// 生成sheet准备写入数据
Sheet sheet = wb.createSheet();
// 取表头
Row headerRow = sheet.createRow(0);
// 设置表头List
List<BaseFieldPo> titleList= new ArrayList<BaseFieldPo>();
add(new BaseFieldPo("userName","姓名"));
add(new BaseFieldPo("type", "类型"));
add(new BaseFieldPo("telPhone","电话号码"));
add(new BaseFieldPo("reason","原因备注"));
// 取表头List
int size = titleList.size();
// 设置表头字段默认宽度(GBK字节数) */
List<Integer> defaultColWidth = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
      Cell cell = headerRow.createCell(i);
      String titlename = titleList.get(i).getName();
      cell.setCellValue(titlename);
      cell.setCellStyle(styles.get("header"));
      try {
                defaultColWidth.add(titlename.getBytes("GBK").length * 2);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                defaultColWidth.add(titlename.length() * 2);
            }
      try {
           defaultColWidth.add(titlename.getBytes("GBK").length * 2);
      } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
           defaultColWidth.add(titlename.length() * 2);
      }
}
// 固定表头
sheet.createFreezePane(0, 1);
// 写入获得的导出结果List
if (dataList != null && dataList.size() > 0) {
    // 写数据
    Row row;
    Cell cell;
    for (int rowNum = 1, j = 0; j < dataList.size(); j++, rowNum++) {
    // 当前待写入的行
    row = sheet.createRow(rowNum);
    // 从list中获取一个对象
    DBObject commHis = dataList.get(j);
    // 从表头挨着去客户对象中查找字段
    for (int k = 0; k < titleList.size(); k++) {
     // 获取第一个字段的值
     Object cellValue = commHis.get(titleList.get(k).getKey());
     cell = row.createCell(k);
     String styleName = "cell_normal";
     if (cellValue == null) {
         cell.setCellValue("");
     } else if (cellValue instanceof String) {
         cell.setCellValue((String) cellValue);
     } else if (cellValue instanceof Integer) {
         cell.setCellValue((Integer) cellValue);
     } else if (cellValue instanceof Long) {
         cell.setCellValue((Long) cellValue);
     } else if (cellValue instanceof Date) {
         cell.setCellValue((Date) cellValue);
         cellValue = "cell_normal_date";
         defaultColWidth.set(j, 20); // 时间字段需要20的宽度
     } else if (cellValue instanceof BasicDBList) {
         cell.setCellValue(((BasicDBList) cellValue).toString());
     } else {
         // should not happen
         cell.setCellValue("N/A");
         SystemLogUtils.Debug("工单中出现未知数据类型 key:" + titleList.get(k).getKey());
     }
         cell.setCellStyle(styles.get(styleName));
  }
 }
}
// 取20英文字符和表头宽度的最大值来确定当前列的宽度
for (int i = 0; i < defaultColWidth.size(); i++) {
     int curColWidth = 20 * 256;
     int defaultWidth = (defaultColWidth.get(i) + 1) * 256;
     if (curColWidth < defaultWidth) {
         sheet.setColumnWidth(i, defaultWidth);
      } else {
          sheet.setColumnWidth(i, curColWidth);
      }
}
// 写文件
try {
     FileOutputStream fileOut = new FileOutputStream(fullPath);
     wb.write(fileOut);
     fileOut.close();
} catch (IOException e) {
      e.printStackTrace();
      throw new ServiceException("写入文件出错 " + e.getMessage());
}
return fileUrl;
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值