java自定義excel

文件下載

本文主要介紹spring boot環境下,利用Apache POI操做Excel,實現Excel文件的在線下載。spring

首先,咱們在這裏介紹一下關於ApachePOI中關於HSSF,XSSF和SXSSF的區別。sql

HSSF是POI工程對Excel 97(-2007)文件操做的純Java實現,使用的 .xls 作結尾的文件
XSSF是POI工程對Excel 2007之後版本 (.xlsx)文件操做的純Java實現,使用 .xlsx 作結尾的文件
從POI 3.8版本開始,提供了一種基於XSSF的低內存佔用的API----SXSSF數據庫

由於Excel版本的不斷升級,就目前使用而言,通常使用較多的是XSSF,而網上大部分教程還停留在老版本(HSSF);SXSSF因爲使用用戶較少,還有很多不適用戶使用習慣的坑未填,對用普通開發者來講較爲複雜,因此只要不是對性能有較強要求的用戶,不建議使用。接下來就主要介紹一下XSSF的使用:app


  1. 首先根據需求建立模板文件,在模板文件中設置好要輸出的列名(表頭),注意要 和sql檢索出來的列名一致
  2. 上代碼
@Override
public void reportsExcelPrint(HttpServletResponse response) {
List<Map<String,Object>> reportList = null;
String projectName="";
//檢索數據庫數據--用來賦值Excel
reportList = projectMapper.selByValue(projectName);
//模板文件路徑
String modalUrl="template/項目週報.xlsx";
//sheet名稱
String sheetName="項目週報";
// 對應數據庫列名--和模板設置的列一致
String[] colKeys={"weekNumber","projectName"};
exportFile(reportList,colKeys,modalUrl,sheetName,response);
}
private void exportFile(List<Map<String, Object>> reportList, String[] colKeys, String modalUrl, String sheetName, HttpServletResponse response) {
    OutputStream out = null;
    try {
        Map<String, Object> results = new HashMap<>();
        results.put("talentFlows", "");
        // 拿到模板文件
        InputStream in = getClass().getClassLoader().getResourceAsStream(modalUrl);
        //新建workbook
        tpWorkbook = new XSSFWorkbook(in);
        //填入數據
        sheet = tpWorkbook.getSheet(sheetName);
        if (reportList != null) {
            //設置表格數據
            setCellData(reportList, colKeys);
        }
        //輸出流
        out = response.getOutputStream();
        response.reset();
        response.setHeader("content-disposition",
                "attachment;filename=" + new String((sheetName).getBytes("gb2312"), "ISO8859-1") + ".xlsx");
        response.setContentType("APPLICATION/msexcel");
        //設置打印對象
        XSSFPrintSetup printSetup = sheet.getPrintSetup();
        //設置打印方向
        printSetup.setLandscape(true);
        // 新建一個Excel的工做空間
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 把模板複製到新建的Excel
        workbook = tpWorkbook;
        // 輸出Excel內容,生成Excel文件
        workbook.write(out);
    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 關閉輸出流
            response.flushBuffer();
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (final IOException e) {
        }
    }
}
/**
* 建立表體數據
* @param data - 表體數據
*/
private void setCellData(List<Map<String, Object>> data, String[] colKeys) {
  //建立表頭
  createHeader();
  //建立合計項變量
  zq_hs = 0;
  int rowSize = 0;
  // 建立數據
  XSSFRow row = null;
  XSSFCell cell = null;
  int i = 3;//startRow:數據開始行
  if (data != null && data.size() > 0) {
      for (int m = 0; m < data.size(); m++) {
          row = sheet.createRow(i);
          if (i == 3) {//第一行
              rowSize = i;
              setCellValue(data, colKeys, row, cell, m);
          } else {
              if (data.get(m).get("blId") == data.get(m - 1).get("blId")) {//相同字段
                  setCellValue(data, colKeys, row, cell, m);
              } else {//合計行
                  if (rowSize != (i - 1)) {//多於1條數據時合併單元格
                      CellRangeAddress cra = new CellRangeAddress(rowSize, i - 1, 2, 2); // 起始行, 終止行, 起始列, 終止列
                      sheet.addMergedRegion(cra);
                      RegionUtil.setBorderBottom(BorderStyle.THIN, cra, sheet);// 下邊框
                      RegionUtil.setBorderRight(BorderStyle.THIN, cra, sheet); // 右邊框
                  }
                  //合計行
                  createTailCellWeekly1(i, zq_hs);
                  zq_hs = 0;
                  i = i + 1;
                  rowSize = i;
                  row = sheet.createRow(i);
                  //下一個模塊
                  setCellValue(data, colKeys, row, cell, m);
              }
              //項目總合計
              if (m == (data.size() - 1)) {
                  if (rowSize != i) {//多於1條數據時合併單元格
                      CellRangeAddress cra = new CellRangeAddress(rowSize, i, 2, 2); // 起始行, 終止行, 起始列, 終止列
                      sheet.addMergedRegion(cra);
                      RegionUtil.setBorderBottom(BorderStyle.THIN, cra, sheet);// 下邊框
                      RegionUtil.setBorderRight(BorderStyle.THIN, cra, sheet); // 右邊框
                  }
                  zq_hsZ = zq_hsZ + zq_hs;
                  //合計行
                  i = i + 1;
                  createTailCellWeekly1(i, zq_hs);
              }
          }
          if (data.size() == 1) {
              //項目總計累加
              zq_hsZ = zq_hsZ + zq_hs;/
              i = i + 1;
              //合計行
              createTailCellWeekly1(i, zq_hs);
          }
          i++;//下一行
          //行賦值完成後,對當前行操做
          styleWeekly(row);
      }
  }
  //建立表尾
  createTailCellWeekly2(i - 1, zq_hsZ, zq_mjZ, hd_hsZ, hd_hs_dzwcZ, hd_mjZ, hd_mj_dzwcZ, azf_rwZ, azf_ykgZ, gd_rwZ, gd_ywc_weekZ);
}
//建立表頭
private void createHeader(String year) {
    // 建立數據
    XSSFCell cell = null;
    XSSFRow row0 = sheet.getRow(0);
    row0.getCell(0).setCellValue(year + "項目計劃表");

    XSSFRow row1 = sheet.getRow(1);
    cell = row1.getCell(10);
    cell.setCellValue(year + "項目投資");
    cell = row1.getCell(16);
    cell.setCellValue(year + "項目oo");
}
/**
 * @return void
 * @Description //TODO 行賦值
 * @Param [data, colKeys, backupType, row, cell, m]
 */
private void setCellValue(List<Map<String, Object>> data, String[] colKeys XSSFRow row, XSSFCell cell, int m) {
    XSSFCellStyle cellStyleTongJi = tpWorkbook.createCellStyle();
    XSSFFont font = tpWorkbook.createFont();
    font.setFontHeightInPoints((short) 36);// 字體大小
    cellStyleTongJi.setFont(font);
    cellStyleTongJi.setBorderBottom(BorderStyle.THIN); // 下邊框
    cellStyleTongJi.setBorderRight(BorderStyle.THIN);// 右邊框
    cellStyleTongJi.setBorderLeft(BorderStyle.THIN);//下邊框
    cellStyleTongJi.setAlignment(HorizontalAlignment.CENTER_SELECTION);//水平對齊
    cellStyleTongJi.setVerticalAlignment(VerticalAlignment.CENTER);//上下對齊
    cellStyleTongJi.setWrapText(true);//自動換行

    XSSFCellStyle cellStyleTongJi1 = tpWorkbook.createCellStyle();
    cellStyleTongJi1.setFont(font);
    cellStyleTongJi1.setBorderBottom(BorderStyle.THIN); // 下邊框
    cellStyleTongJi1.setBorderRight(BorderStyle.THIN);// 右邊框
    cellStyleTongJi1.setAlignment(HorizontalAlignment.LEFT);//水平對齊
    cellStyleTongJi1.setVerticalAlignment(VerticalAlignment.CENTER);//上下對齊
    cellStyleTongJi1.setWrapText(true);//自動換行

    int j = 0;
    for (String key : colKeys) {
        Object colValue = data.get(m).get(key);
        cell = row.createCell(j);
        //後2列文字描述左對齊
        if (key.equalsIgnoreCase("col1") || key.equalsIgnoreCase("col2")) {
            cell.setCellStyle(cellStyleTongJi1);
        } else {
            cell.setCellStyle(cellStyleTongJi);
        }
        if (colValue != null) {
            //單元格賦值
            if (key.equalsIgnoreCase("col3")) {
                cell.setCellValue(colValue.toString() + "地區");
            } else if (key.equalsIgnoreCase("col4")) {
                cell.setCellValue(new BigDecimal(colValue.toString()).stripTrailingZeros().toPlainString());//BigDecimal=>number
            } else if (key.equalsIgnoreCase("col5") || key.equalsIgnoreCase("col6") || ) {
                cell.setCellValue(new BigDecimal(colValue.toString()).stripTrailingZeros().toPlainString());//BigDecimal=>number
            } else {
                cell.setCellValue(colValue.toString());
            }
            //計算合計值
            switch (key) {
                case "planMoveCount":
                    zq_hs += Double.parseDouble(String.valueOf(colValue));
                    break;
                case "planMoveArea":
                    zq_mj += Double.parseDouble(String.valueOf(colValue));
                    break;
                case "mYearCount":
                    hd_hs += Double.parseDouble(String.valueOf(colValue));
                    break;
                case "mWeekCount":
                    hd_hs_dzwc += Double.parseDouble(String.valueOf(colValue));
                    break;
            }
        } else {
            cell.setCellValue("--");
        }
        j++;
    }
}
/**
 * @return void
 * @Description //TODO 建立合計項
 * @Param [size, zq_hs]
 */
private void createTailCellWeekly1(int size, double zq_hs) {
    XSSFCellStyle cellStyleTongJi = tpWorkbook.createCellStyle();
    XSSFFont font = tpWorkbook.createFont();
    font.setBold(true);
    font.setFontHeightInPoints((short) 36);// 字體大小
    cellStyleTongJi.setFont(font);
    cellStyleTongJi.setBorderBottom(BorderStyle.THIN); // 下邊框
    cellStyleTongJi.setBorderRight(BorderStyle.THIN);// 右邊框
    cellStyleTongJi.setBorderLeft(BorderStyle.THIN);//下邊框
    cellStyleTongJi.setAlignment(HorizontalAlignment.CENTER_SELECTION);//水平對齊
    cellStyleTongJi.setVerticalAlignment(VerticalAlignment.CENTER);//上下對齊
    cellStyleTongJi.setWrapText(true);//自動換行

    //合計
    XSSFRow rowTail1 = sheet.createRow(size);
    rowTail1.setHeightInPoints((short) 100);
    sheet.addMergedRegion(new CellRangeAddress(size, size, 0, 2));

    XSSFCell cellTail1 = rowTail1.createCell(0);
    cellTail1.setCellValue("合計");
    cellTail1.setCellStyle(cellStyleTongJi);

    XSSFCell cellTail102 = rowTail1.createCell(1);
    cellTail102.setCellValue("");
    cellTail102.setCellStyle(cellStyleTongJi);

    XSSFCell cellTail103 = rowTail1.createCell(2);
    cellTail103.setCellValue(zq_hs);
    cellTail103.setCellStyle(cellStyleTongJi);
}
/**
 * @return void
 * @Description //TODO 導出完成後格式整理
 * @Param [row]
 */
private void styleWeekly(XSSFRow row){
    for(int k=16;k< 17;k++){
        sheet.autoSizeColumn(k,true);//自適應列寬
        if(row.getCell(k).toString()=="--"){
            row.getCell(k).setCellValue("");
        }
    }
    if(row.getCell(9).toString()!="--"){
        if(row.getCell(3).toString()=="--"){
            row.getCell(3).setCellValue(0);
        }
    }else{
        if(row.getCell(3).toString()=="--"){
            row.getCell(3).setCellValue("--");
        }
    }
}
相關文章
相關標籤/搜索