Word 导入导出

在实际的开发过程中,也会遇到导入导出的功能,今天就简单的做一下总结。

1.需求:将下面word 数据导入到数据库并进行存储

在Controller中

 

    @RequestMapping(value = "/ImportWord")public @RawResponseBodyObject ImportWord(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException,ParseException {return gwyjglyjtzBizc.ImportWord(request, file);}

在Service的实现类中,

 @Overridepublic Object ImportWord(HttpServletRequest request, MultipartFile file) throws ParseException {boolean flag = false;List<String> rowList;String userId = null;String userName = null;String deptId = null;String deptName = null;Map<String, String> userMap = DeptUserUtils.getUserDept(request);if (userMap instanceof Map) {userId = ((Map<?, ?>)userMap).get("userId").toString();userName = ((Map<?, ?>)userMap).get("userName").toString();deptId = ((Map<?, ?>)userMap).get("deptId").toString();deptName = ((Map<?, ?>)userMap).get("deptName").toString();}String xqlb1 = "";String xqdj1 = "";String yjbt1 = "";try {rowList = POIUtils.readYjtzWord(file);GwYjglYjtz gwYjglYjtz = new GwYjglYjtz();for (int i = 0; i < rowList.size(); i++) {if (rowList.get(i).equals("主送单位")) {gwYjglYjtz.setFbdw(rowList.get(++i));}if (rowList.get(i).contains("预警通知")) {yjbt1 += rowList.get(i);}if (rowList.get(i).contains("电缆预警")) {yjbt1 += rowList.get(i);gwYjglYjtz.setYjbt(yjbt1);}if (rowList.get(i).equals("险情类别")) {xqlb1 += rowList.get(++i) + ",";gwYjglYjtz.setXqlb(xqlb1);}if (rowList.get(i).equals("预警来源")) {gwYjglYjtz.setYjly(rowList.get(++i));}if (rowList.get(i).equals("预警级别")) {xqdj1 += rowList.get(++i) + ",";gwYjglYjtz.setXqdj(xqdj1);}if (rowList.get(i).contains("事件概要")) {String string = rowList.get(++i);gwYjglYjtz.setSjgy(string);}if (rowList.get(i).equals("要求")) {gwYjglYjtz.setYgcsyq(rowList.get(i + 1));}if (rowList.get(i).equals("影响时间")) {String string = rowList.get(++i);if (string.length() > 0) {String[] split1 = string.split("~");SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 使用SimpleDateFormat来解析日期字符串SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");// 创建一个新的SimpleDateFormat来格式化输出SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");int a = 0;for (String s : split1) {try {Date date = originalFormat.parse(s);// 转换并打印结果String formattedDate = targetFormat.format(date);System.out.println(formattedDate);if (a == 0) {gwYjglYjtz.setXxkssj(date);} else {gwYjglYjtz.setXxjssj(date);}a++;} catch (Exception e) {e.printStackTrace();}}}gwYjglYjtz.setDjrid(userId);gwYjglYjtz.setDjr(userName);gwYjglYjtz.setDjdwid(deptId);gwYjglYjtz.setDjdw(deptName);gwYjglYjtz.setCreatetime(new Date());}}super.add(gwYjglYjtz);flag = true;System.out.print("导入word成功");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return flag;}

 在这里需要通过输入流的方式把里面的内容读取出来,然后存储到集合中。

    public static List<String> readYjtzWord(MultipartFile formFile) throws IOException {// 检查文件checkDocFile(formFile);InputStream fis = formFile.getInputStream();XWPFDocument document = new XWPFDocument(fis);// 创建返回对象,把每行中的值作为一个数组,所有的行作为一个集合返回List<String[]> list = new ArrayList<String[]>();// 遍历文档中的所有段落List<String> list1 = new ArrayList<String>();List<XWPFParagraph> paragraphs = document.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {// 获取并打印段落文本String text = paragraph.getText();String trim = text.trim();String[] lines = trim.split("\n", 2);for (String s : lines) {list1.add(s);}System.out.println(trim);}// 如果需要处理表格,可以这样获取并遍历List<XWPFTable> tables = document.getTables();for (XWPFTable table : tables) {for (XWPFTableRow row : table.getRows()) {for (XWPFTableCell cell : row.getTableCells()) {for (XWPFParagraph p : cell.getParagraphs()) {String text = p.getText().trim();list1.add(text);System.out.println(text);}}}}// 关闭输入流fis.close();return list1;}

 检查是否是指定文件格式

    public static void checkDocFile(MultipartFile formFile) throws IOException {// 判断文件是否存在if (null == formFile) {logger.error("文件不存在!");throw new FileNotFoundException("文件不存在!");}// 获得文件名// String fileName = formFile.getName();String fileName = formFile.getOriginalFilename();// 判断文件是否是word文件if (!fileName.endsWith(DOC) && !fileName.endsWith(DOCX)) {logger.error(fileName + "不是word文件!");throw new IOException(fileName + "不是word文件!");}}

导出功能

首先我们需要在word 指定对应的模版,对应的字段需要用占位符,这里需要跟数据库的字段需要保持一致或者是和Map 里面的key 。

最终模版制作完成后,保存时请注意,文件类型。一般是xml ,由于电脑的原因我选择的是html 格式。

用编辑器打开编码一定要选择utf-8,不然将来导出的时候是乱码。

编码格式改后,如果还是出现乱码在head 标签中加入一下内容

<head><!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val='Cambria Math'/><m:brkBin m:val='before'/><m:brkBinSub m:val='--'/><m:smallFrac m:val='off'/><m:dispDef/><m:lMargin m:val='0'/> <m:rMargin m:val='0'/><m:defJc m:val='centerGroup'/><m:wrapIndent m:val='1440'/><m:intLim m:val='subSup'/><m:naryLim m:val='undOvr'/></m:mathPr></w:WordDocument></xml><![endif]-->
</head>

 引入对应的jar包

Controller

    @RequestMapping(value = "exportMillCertificate", method = RequestMethod.GET)@ResponseBodypublic void exportMillCertificate(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "objId") String objId) throws Exception {gwyjglyjtzBizc.exportMillCertificate(request, response, objId);}

Service 的实现类

 @Overridepublic void exportMillCertificate(HttpServletRequest request, HttpServletResponse response, String objId)throws Exception {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");// TODO Auto-generated method stubString sql ="select t.yjbt,t.fbdw,t.yjly,t.xqlb,t.xqdj,t.sjgy,t.ygcsyq,to_char(t.xxkssj,'yyyy-MM-dd hh24:mi:ss') as xxkssj,to_char(t.xxjssj,'yyyy-MM-dd hh24:mi:ss') as xxjssj  from  GW_GL_T t  where t.obj_id=?";List<Map<String, String>> list = this.hibernateDao.queryForListWithSql(sql, new String[] {objId});Map<String, String> map0 = new HashMap<String, String>();Map<String, String> map = new HashMap<String, String>();if (!Tool.isEmptyList(list)) {map0 = list.get(0);// 应急标题if (Tool.isEmptyStr(map0.get("yjbt"))) {map.put("yjbt", "");} else {map.put("yjbt", map0.get("yjbt"));}// 发布单位if (Tool.isEmptyStr(map0.get("fbdw"))) {map.put("fbdw", "");} else {map.put("fbdw", map0.get("fbdw"));}// 预警来源if (Tool.isEmptyStr(map0.get("yjly"))) {map.put("yjly", "");} else {map.put("yjly", map0.get("yjly"));}// 险情类别if (Tool.isEmptyStr(map0.get("xqlb"))) {map.put("xqlb", "");} else {map.put("xqlb", map0.get("xqlb"));}// 预警级别if (Tool.isEmptyStr(map0.get("xqdj"))) {map.put("xqdj", "");} else {map.put("xqdj", map0.get("xqdj"));}// 影响时间if (Tool.isEmptyStr(map0.get("xxkssj"))) {map.put("yxsj", "");} else {String string = map0.get("xxkssj");String string1 = map0.get("xxjssj");Date parse = sdf.parse(string);Date parse1 = sdf.parse(string1);String format1 = originalFormat.format(parse);String format2 = originalFormat.format(parse1);map.put("yxsj", format1 + "~" + format2);}// 事件概要if (Tool.isEmptyStr(map0.get("sjgy"))) {map.put("sjgy", "");} else {map.put("sjgy", map0.get("sjgy"));}// 有关措施要求if (Tool.isEmptyStr(map0.get("ygcsyq"))) {map.put("ygcsyq", "");} else {map.put("ygcsyq", map0.get("ygcsyq"));}} else {map.put("yjbt", "");map.put("fbdw", "");map.put("yjly", "");map.put("xqlb", "");map.put("xqdj", "");map.put("yxsj", "");map.put("sjgy", "");map.put("ygcsyq", "");}// map.put("yxsj", "");String yjbt = map0.get("yjbt");WordUtils.exportWord(request, response, map, "yjglyjtzmb.ftl", yjbt);

调用工具类的方法生成Word文档

    public static void exportWord(HttpServletRequest request, HttpServletResponse response, Map<String, String> map,String templateName, String fileName) throws IOException {String pathString = request.getSession().getServletContext().getRealPath("/WEB-INF/templete/");logger.info("获取到的模板路径是:templetePath------->" + pathString);configuration.setDirectoryForTemplateLoading(new File(pathString));Template freemarkerTemplate = configuration.getTemplate(templateName);File file = null;InputStream fin = null;ServletOutputStream out = null;try {// 调用工具类的createDoc方法生成Word文档file = createDoc(map, freemarkerTemplate);fin = new FileInputStream(file);response.setCharacterEncoding("utf-8");response.setContentType("application/msword");// 设置浏览器以下载的方式处理该文件名// + DateUtil.currentDateToString()fileName = fileName + ".doc";response.setHeader("Content-Disposition","attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));out = response.getOutputStream();byte[] buffer = new byte[512]; // 缓冲区int bytesToRead = -1;// 通过循环将读入的Word文件的内容输出到浏览器中while ((bytesToRead = fin.read(buffer)) != -1) {out.write(buffer, 0, bytesToRead);}} finally {if (fin != null)fin.close();if (out != null)out.close();if (file != null)file.delete(); // 删除临时文件}}
    private static File createDoc(Map<String, String> dataMap, Template template) {String name = ".doc";File f = new File(name);Template t = template;try {// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");t.process(dataMap, w);w.close();} catch (Exception ex) {ex.printStackTrace();throw new RuntimeException(ex);}return f;}

最终效果图与导入的是一致里,今天就先到这,在开发过程中不一定会遇到这些,但是觉得还不错那就点赞收藏一波哈,万一哪天用到里。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/48623.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

深入解析Linux目录结构及其功能

深入解析Linux目录结构 Linux 系统的目录结构采用层次化设计&#xff0c;从根目录 / 开始逐级扩展&#xff0c;了解和掌握这些目录的作用和内容有助于我们更好地管理和维护系统。本文将深入解析每个常见目录的功能&#xff0c;并提供相关命令和示例。 目录结构概览 根目录 / …

【BUG】已解决:ERROR: No matching distribution found for PIL

ERROR: No matching distribution found for PIL 目录 ERROR: No matching distribution found for PIL 【常见模块错误】 【解决方案】 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页&#xff0c;我是博主英杰&#xff0c;211科班出身&#xff0…

css大屏设置中间元素四周渐变透明效果

css大屏设置中间元素四周渐变透明效果 四周透明效果&#xff1a; // 设置蒙版上下左右渐变显示mask-image: linear-gradient(to right, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 10%, rgba(0, 0, 0, 1) 90%, rgba(0, 0, 0, 0) 100%),linear-gradient(to bottom, rgba(0, 0, 0…

《Java初阶数据结构》----5.<二叉树的概念及使用>

前言 大家好&#xff0c;我目前在学习java。之前也学了一段时间&#xff0c;但是没有发布博客。时间过的真的很快。我会利用好这个暑假&#xff0c;来复习之前学过的内容&#xff0c;并整理好之前写过的博客进行发布。如果博客中有错误或者没有读懂的地方。热烈欢迎大家在评论区…

6.6 使用dashboard商城搜索导入模板

本节重点介绍 : 模板商城中搜索模板导入模板修改模板 大盘模板商城地址 免费的 地址 https://grafana.com/grafana/dashboards 搜索模板技巧 详情 导入dashboard 两种导入模式 url导入id导入json文件导入 导入 node_exporter模板 https://grafana.com/grafana/dashboa…

流量录制与回放:jvm-sandbox-repeater工具详解

在软件开发和测试过程中&#xff0c;流量录制与回放是一个非常重要的环节&#xff0c;它可以帮助开发者验证系统在特定条件下的行为是否符合预期。本文将详细介绍一款强大的流量录制回放工具——jvm-sandbox-repeater&#xff0c;以及如何利用它来提高软件测试的效率和质量。 …

Python | Leetcode Python题解之第283题移动零

题目&#xff1a; 题解&#xff1a; class Solution:def moveZeroes(self, nums: List[int]) -> None:n len(nums)left right 0while right < n:if nums[right] ! 0:nums[left], nums[right] nums[right], nums[left]left 1right 1

SpringCloud之@FeignClient()注解的使用方式

FeignClient介绍 FeignClient 是 Spring Cloud 中用于声明一个 Feign 客户端的注解。由于SpringCloud采用分布式微服务架构&#xff0c;难免在各个子模块下存在模块方法互相调用的情况。比如订单服务要调用库存服务的方法&#xff0c;FeignClient()注解就是为了解决这个问题的…

汽车免拆诊断案例 | 2014 款上汽名爵 GT 车发动机无法起动

故障现象 一辆2014款上汽名爵GT车&#xff0c;搭载15S4G发动机&#xff0c;累计行驶里程约为18.4万km。该车因左前部发生碰撞事故进厂维修&#xff0c;更换损坏的部件后起动发动机&#xff0c;起动机运转有力&#xff0c;但无着机迹象。用故障检测仪检测&#xff0c;发现无法与…

初识c++:string类(2)

#本节主要讲解c&#xff1a;string类的模拟实现 全部代码的实现在最后面&#xff01;&#xff01;&#xff01;有需要的自己往下滑&#xff0c;自取&#xff01;&#xff01;&#xff01;1.string类的模拟实现 2.浅拷贝 3.深拷贝 目录 #本节主要讲解c&#xff1a;string类…

VIsual Studio:为同一解决方案下多个项目分别指定不同的编译器

一、引言 如上图&#xff0c;我有一个解决方案【EtchDevice】&#xff0c;他包含两个&#xff08;甚至更多个&#xff09;子项目&#xff0c;分别是【DeviceRT】和【DeviceWin】&#xff0c;见名知意&#xff0c;我需要一个项目编译运行在RTOS上&#xff0c;譬如一个名叫INTime…

用重建大师进行空三解算时,引擎出现“不能访问目录或文件”怎么解决?

答&#xff1a;之前的工程还有在做的任务&#xff0c;可以更换任务目录重新提交空三试试。 重建大师是一款专为超大规模实景三维数据生产而设计的集群并行处理软件&#xff0c;输入倾斜照片&#xff0c;激光点云&#xff0c;POS信息及像控点&#xff0c;输出高精度彩色网格模型…

数据中心服务器搬迁团队

数据中心机房服务器搬迁&#xff0c;需要专业的数据中心机房服务器提供技术保障服务。友力科技&#xff08;广州&#xff09;有限公司&#xff0c;作为华南地区主流的数据中心服务商&#xff0c;专业从事数据中心机房搬迁服务。 数据中心机房搬迁涉及设备数量多、系统复杂&…

数据结构: 链表回文结构/分割链表题解

目录 1.链表的回文结构 分析 代码 2.链表分割 ​编辑分析 代码 1.链表的回文结构 分析 这道题的难点是空间复杂度为O&#xff08;1&#xff09; 结合逆置链表找到链表的中间节点就可以解决了。 先找到链表的中间节点&#xff0c;再对中间节点的下一个节点进行逆置&…

什么是大型语言模型 (LLM)

本章探讨下&#xff0c;人工智能如何彻底改变我们理解和与语言互动的方式 大型语言模型 (LLM) 代表了人工智能的突破&#xff0c;它采用具有广泛参数的神经网络技术进行高级语言处理。 本文探讨了 LLM 的演变、架构、应用和挑战&#xff0c;重点关注其在自然语言处理 (NLP) 领…

三、建造者模式

文章目录 1 基本介绍2 案例2.1 Car 类2.2 CarBuilder 抽象类2.3 EconomyCarBuilder 类2.4 LuxuryCarBuilder 类2.5 CarDirector 类2.6 测试程序2.7 测试结果2.8 总结 3 各角色之间的关系3.1 角色3.1.1 Product ( 产品 )3.1.2 Builder ( 抽象建造者 )3.1.3 ConcreteBuilder ( 具…

SvelteKit - 1. 初始化项目

官方 doc - create a project 1、基本环境 &#xff08;下面是我这里的环境&#xff0c;亲测用 node 14 和 16 install 会报错&#xff09; node&#xff1a;20.9.0 npm&#xff1a;10.1.0 2、初始化项目 npm create sveltelatest my-app cd my-app npm install npm run de…

批量打断相交线——ArcGIS 解决方法

在数据处理&#xff0c;特别是地理空间数据处理或是任何涉及图形和线条分析的场景中&#xff0c;有时候需要把相交的线全部从交点打断一个常见的需求。这个过程对于后续的分析、编辑、或是可视化展现都至关重要&#xff0c;因为它可以确保每条线都是独立的&#xff0c;避免了因…

Vue Router基础

Router 的作用是在单页应用&#xff08;SPA&#xff09;中将浏览器的URL和用户看到的内容绑定起来。当用户在浏览不同页面时&#xff0c;URL会随之更新&#xff0c;但页面不需要从服务器重新加载。 1 Router 基础 RouterView RouterView 用于渲染当前URL路径对应的路由组件。…

pytest的安装和介绍和 Exit Code 含义

pytest 准备工作&#xff08;在cmd里&#xff09;&#xff1a; 1安装 pip install -U pytest2验证安装 pytest --version # 会展示当前已安装版本3其他的 显示可用的内置函数参数 pytest --fixtures通过命令行查看帮助信息及配置文件选项 pytest --help一、pytets框架中的…