当前位置: 首页 > news >正文

此网站域名三天更换互联网营销是什么意思

此网站域名三天更换,互联网营销是什么意思,广州网站设计找谁,音乐网站设计素材一般业务系统中都有导出到 Excel 功能,其实质就是把数据库里面一条条记录转换到 Excel 文件上。Java 常用的第三方类库有 Apache POI 和阿里巴巴开源的 EasyExcel 等。另外也有通过 Web 模板技术渲染 Excel 文件导出,这实质是 MVC 模式的延伸&#xff0c…

一般业务系统中都有导出到 Excel 功能,其实质就是把数据库里面一条条记录转换到 Excel 文件上。Java 常用的第三方类库有 Apache POI 和阿里巴巴开源的 EasyExcel 等。另外也有通过 Web 模板技术渲染 Excel 文件导出,这实质是 MVC 模式的延伸,数据转为成不同的视图罢了。

网上很多文章介绍用 Freemarker 模板渲染,应用这一机制的问题不大,本文也是遵循此思路,但没有依赖 Freemarker,而是 Java Servlet 原生的 JSP 模板机制,更加轻量级。

常见的问题

网上文章都介绍模板来自 Excel 另存为 xml 格式的,渲染然后改扩展名为 xls,xml 是文本文件当然可以轻易修改。但致命的问题是,Office Excel 打开的话会有对话框的警告提示,对用户而言非常错愕,用户自然觉得此 Excel 有什么问题,但确认后又可正常显示。在 WPS/LiberOffice 却没有这警告。

在这里插入图片描述
有没有办法绕过这提示呢?直接的方法好像没有,只要是 xml 纯文本的格式就绕不过。我想到了导出 word,同样也是 Freemarker 渲染,但更高明地,使用 zip 压缩包的文档格式,而非 xml 纯文本。我想,能不能在 Excel 上面亦如此炮制呢?

可惜的是,搜遍全网也没发现有类似的思路。但皇天不负有心人,我多次尝试后,亦发现此法可在 Excel 上成功。

使用步骤

新建 Excel 模板

新建 Excel 文档,有标题和模板填充占位符。我喜欢用 LiberOffice 的 Calc,亦无问题。

在这里插入图片描述
诸如${item.orderNo},显然是 JSP 的 EL 表达式。别告诉我你不会,这是最基础的 Java Web 开发内容。item 是固定的,后面的实际字段取值 key。

当然 EL 表达式能够支持的,这里你也同样可以写,如${xxx == 1 ? 'yes' : 'no'},不过建议在前面的数据层面就处理,这里直接显示了。

编辑好模板之后,保存为xlsx格式,注意是 xlsx 而非 xls,因为 xlsx 是 ZIP 压缩包而 xls 不是。

xlsx 文件等下还需要被使用的,将其放到工程的资源目录下。
在这里插入图片描述

提取模板

解压缩这个 xlsx 包,强制解压。这里我用 PeaZip,其他 7Zip、WinRaR 的工具一样。
在这里插入图片描述
找到目录xl/worksheets这里的文件sheet1.xml,1 表示第一个工作簿,如此类推。

在这里插入图片描述
复制这个 sheet1.xml 到 Web 模板可读取的位置。什么意思呢?就是 Servlet 可以渲染此模板,填充数据的目录。这个 xml 是变成 JSP 文件的。根据 Servlet 3.0 规范,META-INF/resources就是 WebRoot,可以放置 HTM/CSS/JS/JSP,就算打包成 SpringBoot 的 jar 包可以。所以,一般这个 xml 就放到META-INF/resources中。

在这里插入图片描述
但又因,这里相当于 WebRoot,浏览器可以直接访问的,那么,放到META-INF/resources/WEB-INF/下似乎更好。

修改模板

当前模板还是 xml,先别急,用代码编辑器(如 VS-code)格式化下先,再改名 jsp 不迟。

然后加入文件头:<%@ page trimDirectiveWhitespaces="true" contentType="text/html; charset=UTF-8" import="java.util.*"%>,不然你会中文乱码的。
在这里插入图片描述
找到刚输入的 EL 表达式部分,要重新梳理下。因为 Excel SharedStrings 的缘故,你很可能找不到那些 EL 表达式字符串,没关系,大概就是节点<sheetData>下的第二个<row>节点(第一个是表头)。

重新梳理后的结果如下:

在这里插入图片描述
列表循环,这里的for很好理解,就是基础 Web 开发知识。

  <%List<Map<String, Object>> list = (List<Map<String, Object>>) request.getAttribute("list");for(Map<String, Object> map : list) {request.setAttribute("item", map);%>

记得for后面的结束括号,别忘了加:
在这里插入图片描述
这里为什么要request.setAttribute("item", map);然后通过 EL 表达式取值呢?为什么不用<%=map.get("xxx")%>? 后者方式也行,但如果是 null 值就会显示 null,${item.statusName}的方式不会。

此时模板就搞定了。

渲染

有模板有数据就可以渲染了。假设是数据是List<Map<String, Object>> list,另外要有对象HttpServletRequest req, HttpServletResponse resp,下面就可渲染了。

Export e = new Export();
e.setIsXsl(true);
e.setIsOfficeZipInRes(true);
e.setTplJsp("/short-trade-new.jsp");
e.setOfficeZip("short-trade.xlsx");
e.setRespOutput(resp, "交易流水 " + DateUtil.now(DateUtil.DATE_FORMAT_SHORTER) + ".xlsx");
e.renderOffice(list, req, resp);

这是渲染到Response的,就是浏览器会直接提示下载的。如果你想保存到文件而非下载。去掉setRespOutput()并设置setOutputPath()保存路径即可。

看看这个单测,就是读取 xml 模板生成 xlsx 的

public static ByteArrayOutputStream p(String path) {File file = new File(path);try (FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {byte[] buffer = new byte[1024];int len;while ((len = fis.read(buffer)) != -1)bos.write(buffer, 0, len);return bos;} catch (IOException e) {e.printStackTrace();}return null;
}@Test
public void replaceXsl() {String newXml = "C:\\code\\car-short-rental\\src\\main\\resources\\META-INF\\resources\\short-trade-new.xml";Export e = new Export();e.setIsXsl(true);e.setOfficeZip("C:\\code\\car-short-rental\\src\\main\\resources\\short-trade.xlsx");e.setOutputPath("C:\\temp\\test.xlsx");e.zip(p(newXml));
//        e.zip(new ByteArrayServletOutputStream(p(newXml)));
}

源码

这个 Office 导出工具包,不但可以导出 Excel 还可以导出 Word 的,三个类去掉注释才 200 多行源码,足够精简。

package com.ajaxjs.tools.office_export;import com.ajaxjs.util.io.Resources;
import com.ajaxjs.util.io.StreamHelper;
import com.ajaxjs.util.logger.LogHelper;
import lombok.Data;import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;/*** Office 导出*/
@Data
public class Export {private static final LogHelper LOGGER = LogHelper.getLog(Export.class);/*** 模板 XML 文件*/private String tplXml;/*** 模板 JSP 文件,必须 / 开头,以及 .jsp 结尾*/private String tplJsp;/*** 原始 docx/xlsx 文档,其实是个 zip 包,我们取其结构,会替换里面的 xml*/private String officeZip;/*** 是否在资源文件目录*/private Boolean isOfficeZipInRes;private File officeZipRes;/*** 导出的 docx/xlsx 位置*/private String outputPath;/*** true=Excel 文件*/private Boolean isXsl;/*** 浏览器下载文件。如果设置该属性,表示浏览器下载文件,否则保存到文件*/private HttpServletResponse respOutput;/*** 浏览器下载文件。如果设置该属性,表示浏览器下载文件,否则保存到文件** @param respOutput 响应对象* @param fileName   下载的文件名*/public void setRespOutput(HttpServletResponse respOutput, String fileName) {this.respOutput = respOutput;respOutput.setContentType("application/vnd.ms-excel");respOutput.setHeader("Content-Disposition", "attachment; filename=\"" + Utils.encodeFileName(fileName) + "\"");}public void renderOffice(Object data, HttpServletRequest req, HttpServletResponse resp) {if (isXsl) {List<Map<String, Object>> list = (List<Map<String, Object>>) data;req.setAttribute("list", list); // 内容数据} else {Map<String, Object> map = (Map<String, Object>) data;for (String key : map.keySet())req.setAttribute(key, map.get(key)); // 内容数据}if (!tplJsp.startsWith("/"))throw new IllegalArgumentException("参数 tplJsp 必须以 / 开头");RequestDispatcher rd = req.getServletContext().getRequestDispatcher(tplJsp);try (ByteArrayServletOutputStream stream = new ByteArrayServletOutputStream();PrintWriter pw = new PrintWriter(new OutputStreamWriter(stream.getOut(), StandardCharsets.UTF_8));) {rd.include(req, new HttpServletResponseWrapper(resp) {@Overridepublic ServletOutputStream getOutputStream() {return stream;}@Overridepublic PrintWriter getWriter() {return pw;}});pw.flush();officeZipRes = input2file(officeZip);zip(stream);officeZipRes.delete();} catch (IOException | ServletException e) {LOGGER.warning(e);}}/*** 替换 Zip 包中的 XML** @param stream 文件流*/void zip(ByteArrayServletOutputStream stream) {zip(stream.getOut());}/*** 替换 Zip 包中的 XML** @param stream 文件流*/void zip(ByteArrayOutputStream stream) {int len;byte[] buffer = new byte[1024];try (ZipFile zipFile = isOfficeZipInRes ? new ZipFile(officeZipRes) : new ZipFile(officeZip); // 原压缩包ZipOutputStream zipOut = new ZipOutputStream(respOutput == null ? Files.newOutputStream(Paths.get(outputPath)) : respOutput.getOutputStream()) /* 输出的 */) {Enumeration<? extends ZipEntry> zipEntry = zipFile.entries();
//            ByteArrayInputStream imgData = img((List<Map<String, Object>>) dataMap.get("picList"), zipOut, dataMap, resXml);String targetXml = isXsl ? "xl/worksheets/sheet1.xml" : "word/document.xml";
//// 开始覆盖文档------------------while (zipEntry.hasMoreElements()) {ZipEntry entry = zipEntry.nextElement();try (InputStream is = zipFile.getInputStream(entry)) {zipOut.putNextEntry(new ZipEntry(entry.getName()));if (entry.getName().indexOf("document.xml.rels") > 0) { //如果是document.xml.rels由我们输入
//                        if (documentXmlRelsInput != null) {
//                            while ((len = documentXmlRelsInput.read(buffer)) != -1) zipOut.write(buffer, 0, len);
//
//                            documentXmlRelsInput.close();
//                        }while ((len = is.read(buffer)) != -1) zipOut.write(buffer, 0, len);} else if (targetXml.equals(entry.getName())) {//如果是word/document.xml由我们输入stream.writeTo(zipOut);} else {while ((len = is.read(buffer)) != -1) zipOut.write(buffer, 0, len);}}}} catch (IOException e) {LOGGER.warning(e);}}/*** 从资源目录中获取文件对象,兼容 JAR 包的方式** @param resourcePath 资源文件* @return 文件对象*/public static File input2file(String resourcePath) {try {File outputFile = File.createTempFile("outputFile", ".docx");// 创建临时文件// 创建输出流try (InputStream input = Resources.getResource(resourcePath);OutputStream output = Files.newOutputStream(outputFile.toPath())) {StreamHelper.write(input, output, false);}return outputFile;} catch (IOException e) {LOGGER.warning(e);}return null;}
}

完整的代码在这里。

参考

  • 使用Freemarker填充模板导出复杂Excel,其实很简单哒!
  • OOXML:详解Excel共享字符串(sharedStrings)
  • 掀开面纱,看看Excel文件到底是什么
  • 使用Freemarker模版导出xls文件使用excel打开提示文件损坏
  • 一次大数据量导出优化–借助xml导出xls、xlsx文件

文章转载自:
http://racism.rzgp.cn
http://corm.rzgp.cn
http://camarilla.rzgp.cn
http://saltatory.rzgp.cn
http://aluminous.rzgp.cn
http://unhung.rzgp.cn
http://patagium.rzgp.cn
http://paralimnion.rzgp.cn
http://megimide.rzgp.cn
http://scrub.rzgp.cn
http://avascular.rzgp.cn
http://eupepticity.rzgp.cn
http://merosymmetry.rzgp.cn
http://camisado.rzgp.cn
http://titian.rzgp.cn
http://tristimulus.rzgp.cn
http://defuze.rzgp.cn
http://annulation.rzgp.cn
http://abruptness.rzgp.cn
http://adrenotropic.rzgp.cn
http://rogue.rzgp.cn
http://bayard.rzgp.cn
http://gloatingly.rzgp.cn
http://avouch.rzgp.cn
http://syndic.rzgp.cn
http://treck.rzgp.cn
http://luce.rzgp.cn
http://hispaniola.rzgp.cn
http://subinfeudate.rzgp.cn
http://recivilize.rzgp.cn
http://trehalose.rzgp.cn
http://bailie.rzgp.cn
http://covalent.rzgp.cn
http://toadyism.rzgp.cn
http://rochdale.rzgp.cn
http://campfire.rzgp.cn
http://macroetch.rzgp.cn
http://sclerotioid.rzgp.cn
http://kittle.rzgp.cn
http://february.rzgp.cn
http://porthole.rzgp.cn
http://unseparated.rzgp.cn
http://shamanism.rzgp.cn
http://ammonotelism.rzgp.cn
http://ganaderia.rzgp.cn
http://economist.rzgp.cn
http://succedanea.rzgp.cn
http://organdie.rzgp.cn
http://thyroidotomy.rzgp.cn
http://braver.rzgp.cn
http://malocclusion.rzgp.cn
http://chartreuse.rzgp.cn
http://starve.rzgp.cn
http://loosely.rzgp.cn
http://aptness.rzgp.cn
http://phonic.rzgp.cn
http://condo.rzgp.cn
http://popgun.rzgp.cn
http://advertise.rzgp.cn
http://longobard.rzgp.cn
http://fuggy.rzgp.cn
http://luluai.rzgp.cn
http://dietary.rzgp.cn
http://boom.rzgp.cn
http://oxytone.rzgp.cn
http://crossbreed.rzgp.cn
http://telomitic.rzgp.cn
http://nannofossil.rzgp.cn
http://ayuntamiento.rzgp.cn
http://belgravia.rzgp.cn
http://forfeitable.rzgp.cn
http://foundryman.rzgp.cn
http://delectus.rzgp.cn
http://fard.rzgp.cn
http://veneration.rzgp.cn
http://seato.rzgp.cn
http://diatessaron.rzgp.cn
http://pandemic.rzgp.cn
http://phototopography.rzgp.cn
http://brashly.rzgp.cn
http://steatitic.rzgp.cn
http://painterly.rzgp.cn
http://boaz.rzgp.cn
http://wherethrough.rzgp.cn
http://alma.rzgp.cn
http://ongoing.rzgp.cn
http://assegai.rzgp.cn
http://yt.rzgp.cn
http://cindery.rzgp.cn
http://paramylum.rzgp.cn
http://explosimeter.rzgp.cn
http://unconfiding.rzgp.cn
http://correlative.rzgp.cn
http://kickup.rzgp.cn
http://preside.rzgp.cn
http://spermatocyte.rzgp.cn
http://katar.rzgp.cn
http://actomyosin.rzgp.cn
http://campanile.rzgp.cn
http://unseconded.rzgp.cn
http://www.dt0577.cn/news/125489.html

相关文章:

  • 一个公司做两个网站的好处推广引流方法有哪些?
  • 银川网站制作八零云自助建站免费建站平台
  • 鹿泉区城乡建设局网站全国十大跨境电商排名
  • 各大网站投稿方式关键字挖掘
  • 做购物网站安全吗北京网站快速优化排名
  • 最权威的做网站设计公司价格怎样建立一个网站
  • 宜城做网站搜索引擎营销的主要方法
  • 做汽车团购的网站google play 安卓下载
  • 科技网站设计资讯广告媒体资源平台
  • 大石桥网站建设互联网运营培训课程
  • 那个网站详情页做的好模板网站建站公司
  • 外国做爰网站如何利用seo赚钱
  • 新加坡二手手机网站大全百度开户渠道商哪里找
  • wordpress aurelius南昌seo排名公司
  • 高州网站建设免费拓客软件
  • 哪个网站可以帮人做ppt站长平台百度
  • wordpress job百度seo关键词工具
  • 做网站实现自动生成pdf备案查询平台官网
  • 自主网站制作长沙seo排名外包
  • 时时彩网站开发公司最佳搜索引擎磁力王
  • html5 电商网站布局吉林seo基础
  • 湖州房产网武汉网站运营专业乐云seo
  • 有哪些企业建设网站手机百度高级搜索入口
  • 建立动态网站的目的网络销售平台排名
  • 怎么用服务器lp做网站优化营商环境建议
  • 备案网站需要多久怎么推广平台
  • 专门做环保设备的网站今日国内新闻大事20条
  • 天天联盟广告网站如何做seo优化顾问服务阿亮
  • 宁乡电商网站建设价格上海seo排名
  • 河北中凯建设有限公司网站免费做网站网站的软件