栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

POI框架学习-导入导出案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

POI框架学习-导入导出案例

目录

一 POI简介

二 行数限制

三 案例(导入和导出)

3.1 导入依赖

3.2 导入案例    

3.3 导出案例(返回文件流方式)

3.4 导出案例(返回URL方式)

3.5 加载模板导出


一 POI简介

        Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。是目前较流行的导入导出excel框架。

        官方网站:Apache POI - the Java API for Microsoft Documentshttps://poi.apache.org/

二 行数限制

        HSSFWorkbook:

                缺点:最多只能处理65536行,否则会抛异常

                优点:过程中写入缓存,不操作磁盘,最后一次性吸入磁盘,速度快

        XSSFWorkbook:最大数据:1048576行,16384列,

                缺点:写数据时速度非常慢,非常耗内存,也会发生内存溢出,如100万条。
                优点:可以写较大数据量,如20万条。

        SXSSFWorkbook:

                优点:可以写非常大的数据量,如100万条甚至更多条写数据速度快,占用更少的内存

        注意:

  1. 过程中会产生临时文件,需要清理临时文件
  2. 默认由100条记录被保存在内存中,如果超过这数量,则最前面的数据被写入临时文件
  3. 如果想自定义内存中数据的数量,可以使用new SXSSFWorkbook(数量)

三 案例(导入和导出)

3.1 导入依赖


       org.apache.poi
       poi
       3.10-FINAL

            

      org.apache.poi
      poi-ooxml
      3.10-FINAL


    org.apache.poi
    poi-ooxml-schemas
    4.1.0

3.2 导入案例    

controller入口:

@PostMapping("import")
public Response importRepayReconciliate(MultipartFile file,HttpServletRequest request){
    try {
        // 判断文件是否为空
        if (!file.isEmpty()) {
            // 文件保存路径
            String message = repayService.import(file.getInputStream(),request);
            return new Response(MessageConstants.MSG_SUCCESS, null, null);
        } else {
            return new Response(MessageConstants.MSG_SYS_ERROR, null, "文件为空,请上传文件!");
        }
    } catch (Exception e) {
        log.error("操作失败,请联系系统管理员!",e,e.getMessage());
        return new Response(MessageConstants.MSG_SYS_ERROR, null, e.getMessage());
    }
}

service类:

Workbook book = WorkbookFactory.create(inputStream); //创建工作簿
Sheet sheet = book.getSheetAt(0);//获取到工作表
int lastRowNum = sheet.getLastRowNum();//获取到表格最后一行
if (lastRowNum < 1 ) {
    return "你未导入任何数据,请添加数据后导入...";
}
Row row = sheet.getRow(2);
Cell cell = row.getCell(1);
String type = cell.getStringCellValue();

row = sheet.getRow(i);
cell = row.getCell(1);
cell.setCellType(CellType.STRING);

// 获取单元格值(为文本重要)
String value = new DataFormatter().formatCellValue(cell);


3.3 导出案例(返回文件流方式)

关键词汇总结:

方式1:

        HSSFWorkbook book = new HSSFWorkbook();  // 有行数限制 不能大于65536行
        HSSFSheet sheet = book.createSheet();

方式2:

        XSSFWorkbook book = new XSSFWorkbook();   // 没有行数限制
        XSSFSheet sheet = book.createSheet();

方式3:

        SXSSFWorkbook book = new SXSSFWorkbook();// 没有行数限制 不占内存(通用)
        book.setCompressTempFiles(true);  //开启压缩配置项

        XSSFRow titleRow = sheet.createRow(0);
        // 设置单元格宽度
        sheet.setColumnWidth(i, 2000); 

        .....

        book.write(out);

        response.flushBuffer();

        book.dispose(); //临时文件需要手动显式删除,调用dispose方法 即可

        out.close();

        book.close();

样式管理:

        样式一HSSF

                HSSFCellStyle cellStyle = book.createCellStyle();

                cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);//设置下面

                cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//设置左边

                cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//设置右边

                cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//设置顶部

                cellStyle.setWrapText(true); //设置自动换行

                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中

                cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中

        样式二-SXSSFWorkbook

                CellStyle cellStyle = book.createCellStyle();

                cellStyle.setBorderBottom(BorderStyle.THIN); //下边框

                cellStyle.setBorderLeft(BorderStyle.THIN);//左边框

                cellStyle.setBorderTop(BorderStyle.THIN);//上边框

                cellStyle.setBorderRight(BorderStyle.THIN);//右边框

                cellStyle.setWrapText(true); //设置自动换行

                cellStyle.setAlignment(HorizontalAlignment.CENTER);// 设置单元格水平居中

                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格垂直居中

合并单元格 起始行 结束行 起始列 结束列

        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));

设置字体

        HSSFFont font = book.createFont();

        font.setBold(true);//设置加粗

        font.setFontHeightInPoints((short) 18);//设置字体大小

        font.setFontName("黑体");//设置字体

        font.setColor(Font.COLOR_RED);//设置字体颜色

        cellStyle.setFont(font);//将字体应用到样式中

克隆样式:

        HSSFCellStyle cellStyle2 = book.createCellStyle();

        cellStyle2.cloneStyleFrom(cellStyle);//克隆之前的样式

行管理:

        HSSFRow row = sheet.createRow(0);

        row.setHeightInPoints(50); //设置行高度

列管理:

        HSSFCell cell = row.createCell(0);

        cell.setCellValue("综合试"); //设置列的值

        cell.setCellStyle(cellStyle); //把样式应用到每个单元格中

controller入口:

@RequestMapping(params = "enterpriseBaseInfoExport")
public void export(JSONObject data,HttpServletRequest request, HttpServletResponse response) {
    try {
        String fileName = "XXX.xls";
        response.setHeader("content-disposition","attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        dataService.export(data,out);
    } catch (Exception e) {
        logger.error("导出错误原因为:" + e.getMessage());
        e.printStackTrace();
    }
}

service常见导出方式:

3.4 导出案例(返回URL方式)

String fileName = UUID.randomUUID().toString().replace("-","");
        String path = request.getSession().getServletContext().getRealPath(File.separator) + File.separator + 
"upload" + File.separator + "download" + File.separator;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        fileName = fileName + ".xlsx";
        String filePath = path + fileName;
        FileOutputStream out = new FileOutputStream(filePath);
        book.setCompressTempFiles(true);
        book.write(out);
        out.close();
        response.flushBuffer();
        book.dispose();  //临时文件需要手动显式删除,调用dispose方法 即可
}

3.5 加载模板导出

模板位置:

XSSFWorkbook wb = new XSSFWorkbook(POIUtil.getInputStream("/statistic/download_template/excel/first_loan_info.xlsx"));
SXSSFWorkbook book = new SXSSFWorkbook(wb);
Sheet sheet = book.getSheetAt(0);
book.setCompressTempFiles(true);

public static InputStream getInputStream(String filePath) throws Exception{
    ClassPathResource classPathResource = new ClassPathResource(filePath);
    if(!classPathResource.exists()){
        throw new RuntimeException("文件不存在:{}"+filePath);
    }
    return classPathResource.getInputStream();
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925205.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号