1. 程式人生 > >POI匯出Excel共通方法

POI匯出Excel共通方法

使用poi外掛封裝,直接上程式碼:

import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CommonExcelUtil<T> {
    @Autowired
    private static EncryptUtil encryptUtil;


    public void setUpExcel(HttpServletResponse response, String table, List list, String fileName) throws IOException {
        String[] tables = table.split(",");
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        //設定列寬
        sheet.setDefaultColumnWidth((short) 18);
        //建立第一行的物件,第一行一般用於填充標題內容。從第二行開始一般是資料
        XSSFRow row = sheet.createRow(0);
        for (short i = 0; i < tables.length; i++) {
            //建立單元格,每行多少資料就建立多少個單元格
            XSSFCell cell = row.createCell(i);
            XSSFRichTextString text = new XSSFRichTextString(tables[i].substring(0, tables[i].indexOf("(")));
            //給單元格設定內容
            cell.setCellValue(text);
        }
        inputStr(sheet, row, list, fileName, tables);

        response.setContentType("application/vnd..ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xlsx");//Excel檔名
        try {
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //將workbook中的內容寫入輸出流中
        workbook.write(response.getOutputStream());
    }

    private void inputStr(XSSFSheet sheet, XSSFRow row, List list, String fileName, String[] tables) {
        List<T> customerList = list;
        //遍歷集合,將每個集合元素物件的每個值填充到單元格中
        for (int i = 0; i < customerList.size(); i++) {
            T statisticsModel = customerList.get(i);
            //從第二行開始填充資料
            row = sheet.createRow(i + 1);
            //該集合只記錄數量和時間,這兩個值來自statisticsModel。如果物件比較複雜,需要額外轉換,比如Date型別的日期,int,float型別的數值
            List<String> dataList = new ArrayList<>();
            Class<?> clz = statisticsModel.getClass();
            for (String table : tables) {
                String fieldName = table.substring(table.indexOf("(") + 1, table.indexOf(")"));
                String methodName = "get" + String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1, fieldName.length());
                try {
                    dataList.add(String.valueOf(clz.getMethod(methodName, null).invoke(statisticsModel)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            ExcelOut(dataList, row);
        }
    }

    /**
     * 資料匯入
     */
    private static void ExcelOut(List<String> dataList, XSSFRow row) {
        for (int j = 0; j < dataList.size(); j++) {
            String str = dataList.get(j);
            XSSFCell cell = row.createCell(j);
            XSSFRichTextString richString = new XSSFRichTextString(str);
            cell.setCellValue(richString);
        }
    }

}

呼叫程式碼:

//傳入列title和對應的取值屬性名
params.setTableTitle("客戶姓名(customerName),年齡(age),性別(sex),業務員(salesman),註冊時間(registDate)");

        customerService.printExcel(params, response);


---------------------------------------------------------------
try {
            CommonExcelUtil<CustomerResultModel> excelUtil = new CommonExcelUtil<>();
            excelUtil.setUpExcel(response, param.getTableTitle(), customers, param.getFileName());
        } catch (IOException e) {
            log.error("匯出客戶資訊列表excel異常", e);
            e.printStackTrace();
        }