使用poi-tl根据富文本编辑器代码生成word下载功能

该博客介绍了如何使用Java后端结合插件生成Word文档,并将多个附件下载后压缩为ZIP文件供前端下载。首先,通过引入poi-tl插件处理HTML内容生成Word文档。然后,在后端处理中,将HTML内容转化为Word并设置响应头以供下载。前端部分通过Vue发送请求,接收响应内容并处理下载。最后,更新代码以同时下载Word文档和附件,将所有附件打包成ZIP供用户下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上干货

 

1、引入插件

       <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.6.0</version>
        </dependency> 

2、后端代码处理

String content = (String) info.get("plancontent");
		//构造完整的html页面,方便组件进行处理
		content = "<html xmlns:v=\"urn:schemas-microsoft-com:vml\"xmlns:o=\"urn:schemas-microsoft-com:office:office\"xmlns:w=\"urn:schemas-microsoft-com:office:word\"xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"xmlns=\"http://www.w3.org/TR/REC-html40\"><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><body>"
				+ content + "</body></html>";
		InputStream is = new ByteArrayInputStream(content.getBytes("utf-8"));
		response.setHeader("Content-Type", "application/msword;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=test.docx");
		ServletOutputStream out = response.getOutputStream();
		POIFSFileSystem fs = new POIFSFileSystem();
		fs.createDocument(is, "WordDocument");
		fs.writeFilesystem(out);
		out.close();
		is.close();

3、前端vue请求方法处理

// 下载
function downloadInfo(data) {
  return request({
    url: '/netFightmap/downloadInfo',
    method: 'post',
    responseType: 'blob',
    data: data
  })
}
    download() {
      this.loading = true;
      downloadInfo({
        id: this.fightmapid,
        userid: this.$store.state.user.userId
      }).then((res) => {
        this.loading = false;
        const content = res
        const blob = new Blob([content])
        const fileName = this.industryMapDetail.customername + '.docx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
        }) .catch((error) => {
          this.loading = false
          console.log(error)
        })
    },

查看效果,

 

 综上,此插件用于在线生成word文档。

这几天需要说要把附件也给下载下来然后压缩一起下载,下面实现的方法如下

Map<String, Object> info = netFightmapService.getInfoAndUpdateNum(id, userId);
		String content = (String) info.get("plancontent");
		String customername = (String) info.get("customername");
		// 构造完整的html页面,方便组件进行处理
		content = "<html xmlns:v=\"urn:schemas-microsoft-com:vml\"xmlns:o=\"urn:schemas-microsoft-com:office:office\"xmlns:w=\"urn:schemas-microsoft-com:office:word\"xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\"xmlns=\"http://www.w3.org/TR/REC-html40\"><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><body>"
				+ content + "</body></html>";
		InputStream is = new ByteArrayInputStream(content.getBytes("utf-8"));
		// 设置响应请求头
		response.setContentType("application/zip");
		response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("附件.zip", "UTF-8"));
		ServletOutputStream out = response.getOutputStream();
		// 生成在线文档,页面转换成word文档
		ByteArrayOutputStream out1 = new ByteArrayOutputStream();
		POIFSFileSystem fs = new POIFSFileSystem();
		fs.createDocument(is, "WordDocument");
		fs.writeFilesystem(out1);
		// 查询所有的附件
		NetAttachmentEntity netAttachmentEntity = new NetAttachmentEntity();
		netAttachmentEntity.setOtherid(id);
		List<NetAttachmentEntity> netAttachmentList = netAttachmentService.getListByObject(netAttachmentEntity);
		ZipOutputStream zipOutputStream = new ZipOutputStream(out);
		// 根据附件id下载文件流
		for (int i = 0; i < netAttachmentList.size(); i++) {
			NetAttachmentEntity attachmentEntity = netAttachmentList.get(i);
			// 文件id
			String fileid = attachmentEntity.getAttachmentfileid();
			// 根据文件id查询文件对应的文件流
			MyFile f = ComFileManager.FileDowload(fileid, "net");
			// 把文件流写入压缩文件流里头然后输出
			ZipEntry zipEntry = new ZipEntry(f.getFileName());
			zipOutputStream.putNextEntry(zipEntry);
			InputStream in = f.getInStream();
			int temp = 0;
			while ((temp = in.read()) != -1) { // 读取内容
				zipOutputStream.write(temp); // 压缩输出
			}
		}
		ZipEntry zipEntry = new ZipEntry(customername + ".docx");
		zipOutputStream.putNextEntry(zipEntry);
		zipOutputStream.write((byte[]) out1.toByteArray());
		if (out1 != null) {
			try {
				out1.close();
			} catch (Exception e2) {
				bizlog.info("下载页面文件--生成在线文件关闭失败", e2);
			}
		}
		if (zipOutputStream != null) {
			try {
				zipOutputStream.close();
			} catch (Exception e2) {
				bizlog.info("下载所有附件--zip实体关闭失败", e2);
			}
		}
		if (out != null) {
			try {
				out.close();
			} catch (Exception e) {
				bizlog.info("下载所有附件--输入缓冲流关闭失败", e);
			}
		}
		if (is != null) {
			try {
				is.close();
			} catch (Exception e) {
				bizlog.info("下载所有附件--输入缓冲流关闭失败", e);
			}
		}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值