POI渲染表格替换指定address参数

  • pom.xml
  • Util工具类
    • 划重点excel文件渲染数据核心方法
    • POJO
    • 下边介绍下小编这里对线上office展示采用的方式
  • 坑!
  • 缺点

pom.xml

        <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-contrib</artifactId><version>3.6</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.17</version></dependency>

Util工具类

我们日常开发中很少将静态问题放置在本地服务器,更多的是放在各种云,例如小编目前就是存储在百度云的BOS中,由于构建poi对象时,小编的方式是根据已有模板创建HSSFWorkbook/XSSFWorkbook,所以首先需要获取模板文件的输入流,BOS的Util中已经提供了获取指定文件输入流的方法,但是! 这个流有问题,根据他不能完成渲染数据,后来没办法,只能先下载到本地,然后再获取输入流,这样最后才成功了。

 /*** 从网络Url中下载文件* 由于linux 与 windows的文件分隔符不一致,所以强烈建议使用 File.separator* urlStr 文件地址* fileName 保存在本地文件的名称* savePath 保存文件的地址 (注意,文件地址与文件名之间添加了file路径)*/public static FileInputStream downLoadFromUrl(String urlStr, String fileName, String savePath) {try {URL url = new URL(urlStr);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//设置超时间为3秒conn.setConnectTimeout(3 * 1000);//防止屏蔽程序抓取而返回403错误
//            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");//得到输入流InputStream inputStream = conn.getInputStream();//获取自己数组byte[] getData = readInputStream(inputStream);//文件保存位置File saveDir = new File(savePath);if (!saveDir.exists()) {saveDir.mkdir();}File file = new File(saveDir + File.separator + "file" + File.separator + fileName);FileOutputStream fos = new FileOutputStream(file);fos.write(getData);fos.close();inputStream.close();return new FileInputStream(saveDir + File.separator + "file" + File.separator + fileName);} catch (IOException e) {e.printStackTrace();}return null;}/*** 从输入流中获取字节数组*/public static byte[] readInputStream(InputStream inputStream) throws IOException {byte[] buffer = new byte[1024];int len = 0;ByteArrayOutputStream bos = new ByteArrayOutputStream();while ((len = inputStream.read(buffer)) != -1) {bos.write(buffer, 0, len);}bos.close();return bos.toByteArray();}

划重点excel文件渲染数据核心方法

/**** 功能描述:** @Auther: 读少* @Date: 2019/3/26 17:25* fileName 文件名称* in 模板文档输入流* out 模板文档输出流* resultValue (这里边封装了要渲染参数的坐标index,以及值value)* startTime,endTime由于小编处理的是数据报表 所以有抄表区间开始时间,截止时间**/public static void applyDataForReport(String fileName, InputStream in, FileOutputStream out,List<ReportFormValue> resultValue, CmReportFormsModel model, String startTime,String endTime) {String copyTimeCellIndex = model.getCopyTimeCellIndex();try {if (fileName.endsWith("xls")) {HSSFWorkbook workbook = new HSSFWorkbook(in);in.close();HSSFSheet sheet = workbook.getSheetAt(0);resultValue.forEach(o -> {CellAddress cellAddress = new CellAddress(o.getIndex());HSSFRow row = sheet.getRow(cellAddress.getRow());if (row == null) {row = sheet.createRow(cellAddress.getRow());}HSSFCell cell = row.getCell(cellAddress.getColumn());if (cell == null) {cell = row.createCell(cellAddress.getColumn());}cell.setCellValue(Double.valueOf(o.getValue()));});if (copyTimeCellIndex != null && !"".equals(copyTimeCellIndex)) {String[] index = copyTimeCellIndex.split(",");for (String tempIndex : index) {CellAddress cellAddress = new CellAddress(tempIndex);HSSFRow row = sheet.getRow(cellAddress.getRow());if (row == null) {row = sheet.createRow(cellAddress.getRow());}HSSFCell cell = row.getCell(cellAddress.getColumn());if (cell == null) {cell = row.createCell(cellAddress.getColumn());}DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");DateTimeFormatter reF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");LocalDateTime.parse(startTime, df).format(reF);cell.setCellValue("抄表区间:" + LocalDateTime.parse(startTime, df).format(reF) + "-" + LocalDateTime.parse(endTime, df).format(reF));}}sheet.setForceFormulaRecalculation(true);workbook.write(out);in.close();out.flush();out.close();} else {//xlxs文件XSSFWorkbook workbook = new XSSFWorkbook(in);in.close();XSSFSheet sheet = workbook.getSheetAt(0);resultValue.forEach(o -> {CellAddress cellAddress = new CellAddress(o.getIndex());XSSFRow row = sheet.getRow(cellAddress.getRow());if (row == null) {row = sheet.createRow(cellAddress.getRow());}XSSFCell cell = row.getCell(cellAddress.getColumn());if (cell == null) {cell = row.createCell(cellAddress.getColumn());}cell.setCellValue(Double.valueOf(o.getValue()));});if (copyTimeCellIndex != null && !"".equals(copyTimeCellIndex)) {String[] index = copyTimeCellIndex.split(",");for (String tempIndex : index) {CellAddress cellAddress = new CellAddress(tempIndex);XSSFRow row = sheet.getRow(cellAddress.getRow());if (row == null) {row = sheet.createRow(cellAddress.getRow());}XSSFCell cell = row.getCell(cellAddress.getColumn());if (cell == null) {cell = row.createCell(cellAddress.getColumn());}DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");DateTimeFormatter reF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");LocalDateTime.parse(startTime, df).format(reF);/***根据指定位置添加,模板渲染时间*/cell.setCellValue("抄表区间:" + LocalDateTime.parse(startTime, df).format(reF) + "-" + LocalDateTime.parse(endTime, df).format(reF));}}sheet.setForceFormulaRecalculation(true);workbook.write(out);in.close();out.flush();out.close();}} catch (Exception e) {e.printStackTrace();System.out.println("渲染数据异常" + e.getMessage());}}

POJO

/*** @author 读少* @date 2019/3/26 17:33* 属性可删减*/
@Data
public class ReportFormValue {private String index;private String value;private Integer pt;private Integer ct;private Integer valueType;private Integer dateType;private String orgMeterCode;private String paramCode;
}
/**** 功能描述: excel模板** @Auther: 读少* @Date: 2019/3/26 17:25*/
@Data
public class CmReportFormsModel {private Integer id;private Integer orgId;private String modelName;private String modelBosUrl;private Integer modelType;private String copyTimeTemplate;private Integer publishStatus;private Integer state;private String creator;private Date createTime;private String updator;private Date updateTime;private String remark;private String copyTimeCellIndex;}

综上服务器端渲染核心代码已完成,其中out输出流,开发者可自行处理,从responset.getOutputStream(),或者new一个输出流写到本地服务器,均可,无非就是返回给前端的方式不一样罢了。

下边介绍下小编这里对线上office展示采用的方式

网址:https://products.office.com/zh-CN/office-online/view-office-documents-online
实现大致效果如下,还可以实现下载,打印,全屏等功能。

坑!

如果表格中存在公式,例如F12 = F11+F10+F9 建议不要采用office编辑文档后上传模板文件,这样这份文件中的公式值在该组件中无法线上显示,需下载后查看,无论xls,xlsx结果都一样。
解决办法,非常骚气,用wps编辑一下表格,触发提示保存,保存之后再重新上传文档就可以在线上查看到公式单元格了。

缺点

由于参数是一个个单元格渲染的,渲染速度还蛮快的,但就是配置是比较繁琐的,只能通过批量导入,或者一个个单月格进行配置要插入的数据项,好在这种功能不需要频繁修改,运维抱着一劳永逸的态度,也就没那么多小脾气了。

POI渲染Excel表格模板替换其中指定表格参数,以及Microsoft联机文档查看器遇到的坑相关推荐

  1. 电大计算机机考excel,中央电大计算机应用机考excel电子表格模板题库存(118页)-原创力文档...

    精品文档 PAGE 1 精品文档 使命:翻开考生文件夹中的EXCEL-2-1.xlsx文件,完结以下操作: (1)用填充柄主动填充"序号",从"380101"开 ...

  2. POI之excel固定模板导出

    POI之excel固定模板导出 一.简介 二.excel模板 三.项目中maven依赖 四.Excel模板操作代码 五.Controller层excel模板导出接口代码 六.导出excel 一.简介 ...

  3. JAVA POI通用Excel导入模板

    JAVA POI通用Excel导入模板 Excel导入模板类 Excel导入模板类 package com.golte.dataform.analysis.controller;import com. ...

  4. python根据模板生成pdf文件_程序生成word与PDF文档的方法(python)

    程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob.Apache POI.Java2Word.iText等各种方式,以及使用free ...

  5. DEDE如何调用指定文章ID来调用特定文档

    这篇文章主要介绍了DEDE如何调用指定文章ID来调用特定文档,具有一定借鉴价值,需要的朋友可以参考下.希望大家阅读完这篇文章后大有收获.下面让小编带着大家一起了解一下.  DEDE怎么调用指定文章ID ...

  6. Excel开发帮助文档查看方法

    Excel开发帮助文档查看方法. 打开Excel 点菜单栏'开发工具',然后点击'visual basic',然后再点'帮助'下第一项,打开帮助文档网页界面,然后再点左侧目录下面的'Excel VBA ...

  7. poi-tl-ext扩展,实现多行表格模板替换

    前言 目前poi-tl只提供了word表格的单行模板渲染能力,但是在实际的开发中,业务需求涉及多行,这里就需要自己编写一个渲染策略. 正文 因为poi-tl使用指定策略的方式为通过ConfigureB ...

  8. anki怎么设置学习计划_新媒体企业品牌营销策划公众号运营规划线上推广内容管理sop工作流程计划方案表格模板新手小白零基础怎么学习写作软文涨粉技巧攻略下载...

    新媒体运营工作总结(共10篇) - 大文斗范文网 ...策划方案(总监级的推广方案) | 秦志强笔记_网络新媒体... 月薪30K新媒体运营在用的线上内容管理营销推广计划sop方案... 教你怎么写好 ...

  9. 如何在html中做一个表格模板,【网页中表格教案】教案表格模板

    第三课 在网页中插入表格 一.教材分析 网页制作中用表格来规划整个网页的布局,是我们设计制作网页常用的手法.所以学会在网页中插入表格是网页制作中的一个重要的部分.本课的主要内容包括在网页中插入表格,表 ...

最新文章

  1. 很多人都在埋怨没有遇到好的团队,但好的团队不可能凭空出现,一流的团队不能仅靠团队成员努力,作为Leader,要有可行的规划,并坚定地执行、时势地调整(转)...
  2. webpack4 高手之路 第四天
  3. 广域网结构和我国通信网的构成
  4. ubuntu20配置阿里源简单粗暴的方法
  5. 【Oracle】查看死锁与解除死锁
  6. 直观理解神经网络和梯度下降
  7. buck变换器设计matlab_一种用于Boost PFC变换器的改进关断时间控制策略
  8. 前端学习(2324):angular初步使用
  9. 数学公式(待慢慢总结)
  10. 免费直播课|Python数据可视化与科学计算可视化案例分享
  11. 中文分词与马尔科夫模型之二:隐马尔科夫模型与维特比
  12. 面向对象-java控制台计算器简单实现[50行]
  13. sscom 中文显示 乱码_SSM框架中的中文乱码问题
  14. 金蝶oracle用鼎信诺取数,取数软件 审计取数软件?
  15. [ROS2 基础] 仿真系统和搭建方法
  16. 正宇控股带你认识区块链技术
  17. Error: unknown command “push“ for “helm“ Helm安装push插件
  18. 韦德高清图片壁纸下载
  19. 如何加粗线条html,PS线条如何加粗,加深?
  20. Linux操作系统下的串口通信

热门文章

  1. NB卡 调试学习记录
  2. Java Plugin Framework (JPF) java插件框架学习
  3. 诡异的楼梯 bfs
  4. 19年3月移动端大厂面试题分享
  5. ubuntu安装mysql 5.7未提示输入密码无法登陆的情况
  6. 降序索引和减轻索引扫描
  7. Certifying Some Distributional Fairness with Subpopulation Decomposition
  8. Y410P用虚拟机装Linux系统,OK6410、Linux2.6.36内核移植,DM9000 驱动移植
  9. 共轭梯度法(FR法)
  10. uniapp小程序订单页面UI