1. 程式人生 > 實用技巧 >poi查詢資料匯出到excel

poi查詢資料匯出到excel

    /**
     * 匯出excel方法
     */
    public void export() throws IOException {
        //1.獲取資料
        List<Paper> list = 查詢的資料;
        //2.建立工作簿
        Workbook wb = new XSSFWorkbook();
        //3.構造sheet
        Sheet sheet = wb.createSheet();
        //4.建立標題
        String [] titles = "論文名稱,第一作者姓名".split(",");
        Row row 
= sheet.createRow(0); int titleIndex=0; for (String title : titles) { Cell cell = row.createCell(titleIndex++); cell.setCellValue(title); } //5.填充資料 int rowIndex = 1; Cell cell=null; for (Paper paper : list) { row
= sheet.createRow(rowIndex++); // 論文名稱 cell = row.createCell(0); cell.setCellValue(paper.getName()); // 第一作者姓名 cell = row.createCell(1); cell.setCellValue(paper.getFirstAuthorName()); } //6.完成下載 ByteArrayOutputStream os = new
ByteArrayOutputStream(); wb.write(os); DownloadUtils.download(os,response,"論文資訊.xlsx"); }
package com.*;

import org.apache.commons.io.output.ByteArrayOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DownloadUtils {

    public static void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/octet-stream");
        fileName = response.encodeURL(new String(fileName.getBytes(),"iso8859-1"));//檔名亂碼問題解決
        response.addHeader("Content-Disposition","attachment;filename="+ fileName);
        response.setContentLength(byteArrayOutputStream.size());
        response.addHeader("Content-Length", "" + byteArrayOutputStream.size());
        ServletOutputStream outputstream = response.getOutputStream();    //取得輸出流
        byteArrayOutputStream.writeTo(outputstream);                    //寫到輸出流
        byteArrayOutputStream.close();                                    //關閉
        outputstream.flush();                                            //刷資料
    }
}