`
ear
  • 浏览: 2547 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

批量导出Excel(.xlsx格式)

阅读更多
直接上代码:
poi版本大于3.8
public class ExcelUtil {
    //声明一个模板工作薄(写入流式数据)
    private Workbook writeDataWorkBook;
    //样式列表
    private Map<String, CellStyle> cellStyleMap;
    //Excel当前数据行数(将要写入数据的索引数)
    private int currentRowNum = 0;
    //数据输出流
    private OutputStream outputStream;
    /**
     * 释放资源
     */
    public void dispose() {
        try {
            if (writeDataWorkBook != null) {
                writeDataWorkBook.write(outputStream);
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
            if (cellStyleMap != null) {
                cellStyleMap.clear();
            }
            cellStyleMap = null;
            outputStream = null;
            writeDataWorkBook = null;
        } catch (IOException e) {
        }
    }

    /**
     * 导出字符串数据
     *
     * @param file        文件名
     * @param columnNames 表头
     * @param sheetTitle  sheet页Title
     */
    public void exportExcelTitle(HttpServletResponse response, String sheetName, List<String> columnNames,
                                  String sheetTitle, List<List<Object>> objects)  {
    //创建xlsx格式的Excel
        XSSFWorkbook wb = new XSSFWorkbook();
        /**
         * SXSSFWorkbook被写入的表格,可进行海量写入
         * 参数:
         * @wb2007版本Excel
         * @100批量写入条数
         */
        SXSSFWorkbook tplWorkBook = new SXSSFWorkbook(wb, 100);
        Map<String, CellStyle> cellStyleMap = styleMap(tplWorkBook);
        // 表头样式
        CellStyle headStyle = cellStyleMap.get("head");
        // 生成一个表格
        Sheet sheet = tplWorkBook.getSheet(sheetName);
        if (sheet == null) {
            sheet = tplWorkBook.createSheet(sheetName);
        }
        // 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum, 0, columnNames.size() - 1));
        // 产生表格标题行
        Row rowMerged = sheet.createRow(currentRowNum);
        Cell mergedCell = rowMerged.createCell(0);
        mergedCell.setCellStyle(headStyle);
        mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
        //写入成功一行数据递增行数
        currentRowNum = currentRowNum + 1;
        // 产生表格表头列标题行
        Row row = sheet.createRow(currentRowNum);
        for (int i = 0; i < columnNames.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(headStyle);
            RichTextString text = new XSSFRichTextString(columnNames.get(i));
            cell.setCellValue(text);
        }
        //写入成功一行数据递增行数
        currentRowNum = currentRowNum + 1;
        //内容样式
        CellStyle contentStyle = cellStyleMap.get("content");
        //正文整数样式
        CellStyle contentIntegerStyle = cellStyleMap.get("integer");
        //正文带小数整数样式
        CellStyle contentDoubleStyle = cellStyleMap.get("double");
        for (List<Object> dataRow : objects) {
            Row row1 = sheet.createRow(currentRowNum);
            for (int j = 0; j < dataRow.size(); j++) {
                Cell contentCell = row1.createCell(j);
               
                Object dataObject = dataRow.get(j);
                contentCell.setCellStyle(contentStyle);
                String str = dataObject.toString();
                if(str.contains("-") && str.contains(":") && str.contains(".0")){
                str.trim();
                str = str.substring(0, str.lastIndexOf(" "));
                contentCell.setCellStyle(contentStyle);
                contentCell.setCellValue(str);
                }else if(this.isNum(str)){
                if(str.contains(".")){
                contentCell.setCellStyle(contentDoubleStyle);
                contentCell.setCellValue(Double.parseDouble(str));
                }else{
                contentCell.setCellStyle(contentIntegerStyle);
                contentCell.setCellValue(Integer.parseInt(str));
                }
                }else{
                contentCell.setCellStyle(contentStyle);
                contentCell.setCellValue(str);
                }
               
            }
            //写入成功一行数据递增行数
            currentRowNum = currentRowNum + 1;
        }
        for(int i = 0 ; i<columnNames.size() ; i ++){
        sheet.autoSizeColumn((short)i); //调整宽度
        }
        try {
        this.setResponseHeader(response, sheetName);
        OutputStream ops = response.getOutputStream();
            tplWorkBook.write(ops);
            ops.flush();
            ops.close();
        } catch (IOException e) {
        }
    }
   
    public void exportExcelCompare(HttpServletResponse response, String sheetName, List<String> columnNames,
            String sheetTitle, List<List<Object>> objects,int length)  {
Workbook tplWorkBook = new XSSFWorkbook();
Map<String, CellStyle> cellStyleMap = styleMap(tplWorkBook);
// 表头样式
CellStyle headStyle = cellStyleMap.get("head");
CellStyle contentStyle = cellStyleMap.get("content");
// 生成一个表格
Sheet sheet = tplWorkBook.getSheet(sheetName);
if (sheet == null) {
sheet = tplWorkBook.createSheet(sheetName);
}
// 合并单元格
sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum, 0, columnNames.size() - 1));
// 产生表格标题行
Row rowMerged = sheet.createRow(currentRowNum);
Cell mergedCell = rowMerged.createCell(0);
mergedCell.setCellStyle(headStyle);
mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
//写入成功一行数据递增行数
currentRowNum = currentRowNum + 1;
// 产生表格表头列标题行
Row row = sheet.createRow(currentRowNum);
sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum, 0,length));
sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum, length+1,length*2+1));
Cell headerCell = row.createCell(0);
headerCell.setCellStyle(contentStyle);
headerCell.setCellValue("民航局");
Cell headerCells = row.createCell(8);
headerCells.setCellStyle(contentStyle);
headerCells.setCellValue("空管局");
//写入成功一行数据递增行数
currentRowNum = currentRowNum + 1;
//正文整数样式
CellStyle contentIntegerStyle = cellStyleMap.get("integer");
//正文带小数整数样式
CellStyle contentDoubleStyle = cellStyleMap.get("double");
for (List<Object> dataRow : objects) {
Row row1 = sheet.createRow(currentRowNum);
for (int j = 0; j < dataRow.size(); j++) {
Cell contentCell = row1.createCell(j);
Object dataObject = dataRow.get(j);
contentCell.setCellStyle(contentStyle);
String str = dataObject.toString();
if(str.contains("-") && str.contains(":") && str.contains(".0")){
str.trim();
str = str.substring(0, str.lastIndexOf(" "));
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(str);
}else if(this.isNum(str)){
if(str.contains(".")){
contentCell.setCellStyle(contentDoubleStyle);
contentCell.setCellValue(Double.parseDouble(str));
}else{
contentCell.setCellStyle(contentIntegerStyle);
contentCell.setCellValue(Integer.parseInt(str));
}
}else{
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(str);
}

}
//写入成功一行数据递增行数
currentRowNum = currentRowNum + 1;
}
for(int i = 0 ; i<columnNames.size() ; i ++){
sheet.autoSizeColumn((short)i); //调整宽度
}
try {
this.setResponseHeader(response, sheetName);
OutputStream ops = response.getOutputStream();
tplWorkBook.write(ops);
ops.flush();
ops.close();
} catch (IOException e) {
}
}
   
   

    /**
     * 设置响应头
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
             fileName = new String(fileName.getBytes(),"ISO8859-1");
             response.setContentType("application/octet-stream;charset=ISO8859-1");
             response.setHeader("Content-Disposition", "attachment;filename="+ fileName+".xlsx");
             response.addHeader("Pargam", "no-cache");
             response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
             ex.printStackTrace();
        }
   }
    /**
     * 判断是否是数值型数据
     */
    public boolean isNum(String str) {
 
        try {
            new BigDecimal(str);
            if(str.contains("E")){
            return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 单元格样式(Integer)列表
     */
    private CellStyle createCellContent4IntegerStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //设置对齐样式
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成字体
        Font font = workbook.createFont();
        // 正文样式
        style.setFillPattern(XSSFCellStyle.NO_FILL);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);
        style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));//数据格式只显示整数
        return style;
    }

    /**
     * 单元格样式(Double)列表
     */
    private CellStyle createCellContent4DoubleStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //设置对齐样式
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成字体
        Font font = workbook.createFont();
        // 正文样式
        style.setFillPattern(XSSFCellStyle.NO_FILL);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);
        style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));//保留两位小数点
        return style;
    }
    /**
     * 创建单元格表头样式
     *
     * @param workbook 工作薄
     */
    private CellStyle createCellHeadStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //设置对齐样式
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成字体
        Font font = workbook.createFont();
        // 表头样式
        style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        return style;
    }

    /**
     * 创建单元格正文样式
     *
     * @param workbook 工作薄
     */
    private CellStyle createCellContentStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        //设置对齐样式
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成字体
        Font font = workbook.createFont();
        // 正文样式
        style.setFillPattern(XSSFCellStyle.NO_FILL);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style.setFont(font);
        return style;
    }
    /**
     * 单元格样式列表
     */
    private Map<String, CellStyle> styleMap(Workbook workbook) {
        Map<String, CellStyle> styleMap = new LinkedHashMap<String, CellStyle>();
        styleMap.put("head", createCellHeadStyle(workbook));
        styleMap.put("content", createCellContentStyle(workbook));
        styleMap.put("integer", createCellContent4IntegerStyle(workbook));
        styleMap.put("double", createCellContent4DoubleStyle(workbook));
        return styleMap;
    }
}
分享到:
评论

相关推荐

    Access批量转Excel(支持WIN11)

    1.Access批量转Excel(支持WIN11) 2.支持一键全选,反选,不选 3.导出.xlsx文件 4.按每个表生成一个文件,或合成一个文件。

    如何利用Python把excel中的内容批量替换到word中

    ****************** 说明 ****************** 1.excel不能合并单元格 2.excel表头必须是第一行,并且不能为...4.word只支持.docx,excel只支持.xls/.xlsx 格式 5.word模板占位符格式:{xxx},xxx:是excel中表头列的名字

    golang实现的读取excel模板批量生成excel工具.zip

    golang实现的读取excel模板批量生成excel工具,内含脚本文件及32位版的exe,可直接运行

    Python把excel中的内容批量替换到word中

    Python把excel中的内容批量替换到word中 需要把excel里表格的数据复制到word文档中,比如excel中的公司名称...4.word只支持.docx,excel只支持.xls/.xlsx 格式 5.word模板占位符格式:{xxx},xxx:是excel中表头列的名字

    opencart 商品批量导入导出插件(excel格式可编辑)

    opencart 商品批量导入导出插件(excel格式可编辑)

    测试用例设计模板.xlsx

    很多有大量数据处理的系统都有批量导入导出功能。导入导出的文件格式通常为Excel文件。对于导入导出功能也是个测试的难点和复杂点,总结主要测试点有以下内容:

    Office批量打印精灵一款Office文档批量打印软件.rar

    支持多种格式Office文档的批量打印,支持Excel格式:xls,xlsx;支持Powerpoint格式:ppt,pps,pot,pptx;支持Word格式:doc,vri,wps,rtf,txt,text,docx。  Office批量打印精灵可使用虚拟打印机,将多个...

    Excel逐行导出为TXT

    将要导出的excel的文件名改为a.xls,将VBS和该文档放在同一个文件夹内即可。

    java读取excel所需jar包(xlsx导出并附带其他数据库连接基本jar包)

    里面写了含有写好的EXCEL方法,支持大数据批量导出,最新的xlsx文件

    Excel文档批量转换-xls2xlsx

    系统导出的Excel表格格式通常是xls,有时候需要的是xlsx,文件多的话手工转换比较麻烦,利用这个软件,可以批量处理xls表格,并且可以删除指定前几行,以及转换后自动删除原xls表格。

    Excel文档批量转换-csv2xlsx

    系统导出的Excel表格格式通常是csv,有时候需要的是xlsx,文件多的话手工转换比较麻烦,利用这个软件,可以批量处理xls表格,并且可以删除指定前几行,以及转换后自动删除原csv表格。

    基于js-xlsx的前端excel导入导出工具

    ## excel导入导出工具 在需要使用的地方导入方法: ```javascript import { importExcel, exportExcel } from '@/util/excel' ``` 导入excel并转化为JSON: ```javascript // file: excel文件 // keys: 数组 excel每个...

    Office批量打印精灵4.0.zip

    支持Excel格式:*.xlsx、*.xlsm、*.xlsb、*.xlam、*.xltx、*.xltm、*.xls、*.xla、*.xlt、*.xlm、*.xlw、*.csv 等; 支持Powerpoint格式:*.pptx、*.ppt、*.pptm、*.ppsx、*.pps、*.ppsm、*.potx、*.pot、*.potm、*...

    Office批量打印精灵4.1.zip

    免费、高效、批量打印! Office批量打印精灵是一款Office文档批量打印软件,支持Word、Excel、...支持Excel格式:xls,xlsx;  2.支持Powerpoint格式:ppt,pps,pot,pptx;  3.支持Word格式:doc,vri,wps

    spring+angular实现导出excel的实现代码

    要求批量导出数据,以excel的格式。 选择方式 前台 + 后台 之前在别的项目中也遇到过导出的问题,解决方式是直接在前台导出将表格导出。 这次没有选择前台导出的方式,是由于需要导出所有的数据,所以考虑直接在...

    Office批量打印精灵 v3.1.zip

    支持多种格式Office文档的批量打印,支持Excel格式:xls,xlsx;支持Powerpoint格式:ppt,pps,pot,pptx;支持Word格式:doc,vri,wps,rtf,txt,text,docx。可使用虚拟打印机,将多个Office文档转换为PDF文件...

    matlab批量读取excel表格数据并处理画图

    批量读取全部sheet内容,可指定,并对无效内容处理,提取所需数据并画图

    Qt的ts文件转换成excel文件

    使用python将ts文件格式化为excel文件,使用方法,将需要操作的ts文件改名为en2zh.ts,置于exe同级目录下,执行exe即可,输出文件为en2zh.xlsx。 ****** 注:如有定制化处理需求,或者任何相关问题可通过邮箱联系...

    将txt导入excel 快速将txt转换成excel (2.16版)

    9.如果你安装过office2007然后又卸载重新安装回office2003而且office2007卸载的时候没卸载干净,那么这个软件很有可能会把Excel生成office2007的格式,囧。 解决办法是在开始&gt;运行-&gt;输入“regedit”(打开注册表编辑...

    xlsx课表转ics日历格式文件

    讲xlsx文件的课表,转成ics格式,然后就可以批量的将课表添加到日历中。以实现对生活更有逻辑的管理

Global site tag (gtag.js) - Google Analytics