1. 程式人生 > >JAVA匯出excel總結

JAVA匯出excel總結

一般匯出excel分為2步,第一步為查詢需要匯出的資料,這個就不做闡述了,查詢出一個list,然後開始匯出excel:

首先,匯出excel需要依賴一下jar包:

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.16</version>

</dependency>

<dependency>

<groupId>org.apache.poi</

groupId>

<artifactId>poi-ooxml</artifactId>

<version>3.16</version>

</dependency>

再把要匯入的每一個title放到list裡:

  public List<String> exportTitleMake(XSSFSheet sheet) {

    List<String> title = Lists.newArrayList();
    title.add("匯出測試");

return title;

}

然後開始匯出

XSSFWorkbook workbook = new XSSFWorkbook();
OutputStream outputStream = null;
try {
    workbook.createSheet();
    XSSFSheet sheet = workbook.getSheetAt(0); //主要表單
    CellStyle style = workbook.createCellStyle(); // 樣式物件
    style.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直
    style.setAlignment(HorizontalAlignment.CENTER);// 水平
    style.setWrapText(true);//自適應

    List<String> title = exportTitleMake(sheet);
    ExcelTools.createRow(sheet, 0, title);
    int i = 1;
    for (int j = 0; j < 10; j++) {
        title.clear();
        title.add("");

        ExcelTools.createRow(sheet, i++, title);
    }
    ResponseHeaderForExcel.setResponseHeader(request, response, "匯出測試");
    outputStream = response.getOutputStream();
    workbook.write(outputStream);
    return true;
} catch (Exception e) {
    log.error("failed to export, cause: {}", Throwables.getStackTraceAsString(e));
    throw new JsonResponseException("export.fail");
}finally {
    try {
        workbook.close();
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    } catch (IOException io) {
        log.error("failed to close workbook, cause:{}", Throwables.getStackTraceAsString(io));
    }
}

for迴圈篩選出來的資料,然後title.add進去即可,注意每次add之前都要clear一下,最好不要使用clear,最好直接new 一個,就好了,下載excel的程式碼:

public abstract class ResponseHeaderForExcel {

    public static void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String fileName)
            throws UnsupportedEncodingException {
        fileName = fileName + ".xlsx";

        final String userAgent = request.getHeader("USER-AGENT");

        String finalFileName;
        if(StringUtils.contains(userAgent.toUpperCase(), "MSIE")
                || StringUtils.contains(userAgent.toUpperCase(), "TRIDENT")
                || StringUtils.contains(userAgent.toUpperCase(), "EDGE")   ){//IE瀏覽器
            finalFileName = URLEncoder.encode(fileName,"UTF8");
        }else if(StringUtils.contains(userAgent.toUpperCase(), "Mozilla".toUpperCase())){//safari,火狐瀏覽器
            finalFileName = new String(fileName.getBytes(), "ISO8859-1");
        }else{
            finalFileName = URLEncoder.encode(fileName,"UTF8");//其他瀏覽器, 如chrome等
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");
        response.setContentType("application/octet-stream;charset=utf-8");
    }

}

給excel每個單元格賦值的方法:

public static void createRow(Sheet sheet, int rowNum, List<String> contents) {
    Workbook workbook = sheet.getWorkbook();
    CellStyle textStyle;
    if (workbook.getNumCellStyles() > 0) {
        textStyle = workbook.getCellStyleAt(0);
    } else {
        textStyle = workbook.createCellStyle();
    }
    DataFormat format = workbook.createDataFormat();
    textStyle.setDataFormat(format.getFormat("@"));
    CellStyle style;
    if (workbook.getNumCellStyles() == 0) {
        style = workbook.createCellStyle();

    } else {
        style = workbook.getCellStyleAt(0);
    }
    style.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直
    style.setAlignment(HorizontalAlignment.CENTER);// 水平
    style.setWrapText(true);//自適應
    Row row = sheet.createRow(rowNum);
    row.setRowStyle(style);
    for (int i = 0; i < contents.size(); i++) {
        Cell cell = row.createCell(i);
        cell.setCellStyle(style);
        DataFormat df = workbook.createDataFormat();
        if (contents.get(i) == null) {
            cell.setCellValue("");
        } else if (isNumeric(contents.get(i))) {
            cell.setCellType(CellType.NUMERIC);
            cell.setCellValue(Double.parseDouble(contents.get(i)));
            textStyle.setDataFormat(df.getFormat("#,##0.00"));
        } else {
            cell.setCellType(CellType.STRING);
            cell.setCellValue(contents.get(i));
        }
    }
}

就ok了

ps:會有個問題,就是匯出excel報錯,但是可以正常匯出,報的錯是:org.eclipse.jetty.io.EofException: Closed

網上搜了一下說是記憶體不足,可是實際上我只匯出來兩三條資料,後來發現是介面設定了返回boolean型別,改成void就行了,原因是返回了一個檔案,又返回了一個boolean值,跟http的header有關,具體沒研究