原生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;
    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,204评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,091评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,548评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,657评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,689评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,554评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,302评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,216评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,661评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,851评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,977评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,697评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,306评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,898评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,019评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,138评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,927评论 2 355

推荐阅读更多精彩内容