原生POI導出-進階版

package org.ctzk.jcpc.utils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * org.ctzk.jcpc.utils
 *
 * @author luozhen
 * @version V1.0
 * @date 2020-2-5 11:28
 * @description
 */

public class ExcelUtil {

    private String srcXlsPath = "";// // 導入excel模板路徑
    private String desXlsPath = "";
    private String sheetName = "";

    CellStyle cellStyle = null;

    POIFSFileSystem fs = null;
    HSSFWorkbook wb = null;
    HSSFSheet sheet = null;

    /**
     * 第一步、設置excel模板路徑
     *
     * @param srcXlsPath
     */
    public void setSrcPath(String srcXlsPath) {
        this.srcXlsPath = srcXlsPath;
    }

    /**
     * 第二步、設置要生成excel文件路徑
     *
     * @param desXlsPath
     */
    public void setDesPath(String desXlsPath) {
        this.desXlsPath = desXlsPath;
    }

    /**
     * 第三步、設置模板中哪個Sheet列
     *
     * @param sheetName
     */
    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }

    /**
     * 第四步、獲取所讀取excel模板的對象
     */
    public void getSheet() {
        try {
            File fi = new File(srcXlsPath);
            if (!fi.exists()) {
                System.out.println("模板文件:" + srcXlsPath + "不存在!");
                return;
            }
            fs = new POIFSFileSystem(new FileInputStream(fi));
            wb = new HSSFWorkbook(fs);
            cellStyle = getStyle(wb);
            sheet = wb.getSheet(sheetName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 第五步、設置字符串類型的數據
     *
     * @param rowIndex --行值
     * @param cellnum  --列值
     * @param value    --字符串類型的數據
     */
    public void setCellStrValue(int rowIndex, int cellnum, String value) {
        HSSFRow row = sheet.getRow(rowIndex);
        if (null == row) {
            row = sheet.createRow(rowIndex);
        }
        HSSFCell cell = row.getCell(cellnum);
        if (null == row.getCell(cellnum)) {
            cell = row.createCell(cellnum);
        }
        cell.setCellValue(value);
        cell.setCellStyle(cellStyle);
    }

    /**
     * 第五步、設置日期/時間類型的數據
     *
     * @param rowIndex --行值
     * @param cellnum  --列值
     * @param value    --日期/時間類型的數據
     */
    public void setCellDateValue(int rowIndex, int cellnum, Date value) {
        Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
        if (null != value) {
            cell.setCellValue(value);
        }
    }

    /**
     * 第五步、設置浮點類型的數據
     *
     * @param rowIndex --行值
     * @param cellnum  --列值
     * @param value    --浮點類型的數據
     */
    public void setCellDoubleValue(int rowIndex, int cellnum, double value) {
        Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
        cell.setCellValue(value);
    }

    /**
     * 第五步、設置Bool類型的數據
     *
     * @param rowIndex --行值
     * @param cellnum  --列值
     * @param value    --Bool類型的數據
     */
    public void setCellBoolValue(int rowIndex, int cellnum, boolean value) {
        Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
        cell.setCellValue(value);
    }

    /**
     * 第五步、設置日歷類型的數據
     *
     * @param rowIndex --行值
     * @param cellnum  --列值
     * @param value    --日歷類型的數據
     */
    public void setCellCalendarValue(int rowIndex, int cellnum, Calendar value) {
        Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
        if (null != value) {
            cell.setCellValue(value);
        }
    }

    /**
     * 第五步、設置富文本字符串類型的數據。可以為同一個單元格內的字符串的不同部分設置不同的字體、顏色、下劃線
     *
     * @param rowIndex --行值
     * @param cellnum  --列值
     * @param value    --富文本字符串類型的數據
     */
    public void setCellRichTextStrValue(int rowIndex, int cellnum, RichTextString value) {
        Cell cell = sheet.getRow(rowIndex).getCell(cellnum);
        cell.setCellValue(value);
    }

    /**
     * 第六步、完成導出 type=0,不會修改表格名 type=1,修改表格名依次為當日日期,明日日期,后天日期,遞增
     */
    public void exportToWeb(HttpServletResponse response, String fileName) {
        OutputStream out = null;
        String encodedfileName = "";
        try {
            if (fileName.toLowerCase().endsWith(".xls")) {

                encodedfileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            } else {
                encodedfileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1") + ".xls";
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
            response.setContentType("application/vnd.ms-excel");
            out = response.getOutputStream();
            out.flush();
            wb.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //關閉流
                out.close();
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 根據模版導出Excel(2007及以上版本)
     *
     * @param response     響應對象
     * @param tempFileName 模版文件名
     * @param outFileName  輸出文件名
     * @param sheetIndex   Sheet頁簽索引,從0開始
     * @param startRow     開始行,從0開始
     * @param startCell    開始列,從0開始
     * @param dataList     數據集合,不能為空
     */
    public static void exportExcelByTemp07(HttpServletResponse response, String tempFileName, String outFileName, Integer sheetIndex, Integer startRow, Integer startCell, List<LinkedHashMap<String, Object>> dataList) {
        Workbook wb = null;
        InputStream is = null;
        try {
            is = new FileInputStream(getFilePath(tempFileName));
            // 第一步:創建工作空間,對應Excel文件
            wb = new XSSFWorkbook(is);
            // 第二步:向工作工作空間中寫入內容
            exportExcelByTemp(wb, sheetIndex, startRow, startCell, dataList);
            // 第三步:將文件輸出到客戶端瀏覽器
            outExcelToClient(response, wb, outFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String getFilePath(String fileName) throws UnsupportedEncodingException {
        String root = ExcelUtil.class.getResource("/").getPath();
        if (root.indexOf("target") >= 0) {
            root = root.substring(1, root.indexOf("target"));
            root = root.replaceAll("/", "\\\\");
            root = root + "src\\main\\webapp" + File.separator + "excle_model" + File.separator + fileName;
        } else {
            root = root.substring(1, root.indexOf("WEB-INF"));
            root = root.replaceAll("/", "\\\\");
            root = root + "excle_model" + File.separator + fileName;
        }

        return URLDecoder.decode(root, "GBK");
    }

    /**
     * 根據模版導出Excel
     *
     * @param wb         工作空間,對應Excel文件
     * @param sheetIndex Sheet頁簽索引,從0開始
     * @param startRow   開始行,從0開始
     * @param startCell  開始列,從0開始
     * @param dataList   數據集合,不能為空
     */
    private static void exportExcelByTemp(Workbook wb, Integer sheetIndex, Integer startRow, Integer startCell, List<LinkedHashMap<String, Object>> dataList) {
        // Sheet頁簽,從0開始
        sheetIndex = (sheetIndex != null && sheetIndex > 0) ? sheetIndex : 0;

        // 第一步:獲取Sheet頁簽
        Sheet sheet = wb.getSheetAt(sheetIndex);
        // 如果頁簽不存在,則創建頁簽
        sheet = sheet != null ? sheet : wb.createSheet();
        if (dataList != null && dataList.size() > 0) {
            // 開始行
            startRow = (startRow != null && startRow > 0) ? startRow : 0;
            // 開始列
            startCell = (startCell != null && startCell > 0) ? startCell : 0;
            // 樣式(畫筆)
            CellStyle cellStyle = getStyle(wb);

            for (int i = 0, size = dataList.size(); i < size; i++) {
                // 第二步:獲取行
                // Row row = sheet.getRow(startRow + i);
                Row row = sheet.createRow(startRow + i);
                // 設置行高
                row.setHeightInPoints(20);

                LinkedHashMap<String, Object> dataMap = dataList.get(0);
                int j = 0;
                for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                    // 第三步: 獲取單元格
                    Cell cell = row.createCell(startCell + j);
                    // Cell cell = row.getCell(startRow + j);
                    // 設置單元格類型為字符串
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue(String.valueOf(entry.getValue()));
                    cell.setCellStyle(cellStyle);
                    j++;
                    entry = null;
                }

                dataList.remove(0);
            }
        }
    }

    /**
     * 輸入Excel文件到客戶端
     *
     * @param response 響應對象
     * @param wb       工作空間,對應一個Excel文件
     * @param fileName Excel文件名
     */
    private static void outExcelToClient(HttpServletResponse response, Workbook wb, String fileName) {
        OutputStream out = null;
        try {
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.ms-excel; charset=UTF-8");
            out = response.getOutputStream();
            wb.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 獲取樣式
     *
     * @param wb 工作空間
     * @return
     */
    private static CellStyle getStyle(Workbook wb) {
        // 設置字體;
        Font font = wb.createFont();
        // 設置字體大小;
        font.setFontHeightInPoints((short) 12);
        // 設置字體名字;
        font.setFontName("宋體");
        // font.setItalic(true); // 斜體
        // font.setStrikeout(true); // 刪除線
        // 設置樣式;
        CellStyle style = wb.createCellStyle();
        // 設置底邊框;
        style.setBorderBottom(BorderStyle.THIN);

        // 設置底邊框顏色;
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        // 設置左邊框;
        style.setBorderLeft(BorderStyle.THIN);
        // 設置左邊框顏色;
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        // 設置右邊框;
        style.setBorderRight(BorderStyle.THIN);
        // 設置右邊框顏色;
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        // 設置頂邊框;
        style.setBorderTop(BorderStyle.THIN);
        // 設置頂邊框顏色;
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        // 在樣式用應用設置的字體;
        style.setFont(font);
        // 設置自動換行;
        style.setWrapText(false);
        // 設置水平對齊的樣式為居中對齊;
        style.setAlignment(HorizontalAlignment.CENTER);
        // 設置垂直對齊的樣式為居中對齊;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容