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

直接上干货

 

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);
			}
		}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Poi-tl库根据Word模板填充内容生成Word文档时,可以使用Poi-tl提供的模板语法来处理空值。以下是一个示例代码: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter; import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.Document; import org.apache.poi.xwpf.usermodel.HeaderFooterType; import org.apache.poi.xwpf.usermodel.IBodyElement; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class WordTemplateFiller { public static void main(String[] args) { try { // 加载Word模板文件 FileInputStream templateStream = new FileInputStream("template.docx"); XWPFDocument document = new XWPFDocument(templateStream); // 填充内容 Map<String, Object> placeholders = new HashMap<>(); placeholders.put("name", "John Doe"); placeholders.put("age", "30"); placeholders.put("address", ""); replacePlaceholders(document, placeholders); // 保存填充后的文档 FileOutputStream outputStream = new FileOutputStream("filled_template.docx"); document.write(outputStream); outputStream.close(); System.out.println("Word文档生成成功!"); } catch (IOException e) { e.printStackTrace(); } } private static void replacePlaceholders(XWPFDocument document, Map<String, Object> placeholders) { for (XWPFParagraph paragraph : document.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null) { for (Map.Entry<String, Object> entry : placeholders.entrySet()) { String placeholder = "${" + entry.getKey() + "}"; if (text.contains(placeholder)) { Object value = entry.getValue(); if (value != null && !value.toString().isEmpty()) { text = text.replace(placeholder, value.toString()); } else { text = text.replace(placeholder, ""); // 替换为空字符串 } run.setText(text, 0); } } } } } } } ``` 在上述代码中,我们首先加载Word模板文件,然后定义了一个`placeholders`的映射,其中包含了要替换的占位符和对应的值。接下来,我们调用`replacePlaceholders`方法来替换文档中的占位符。 在`replacePlaceholders`方法中,我们遍历文档中的每个段落和文本运行,通过检查文本内容中是否包含占位符来确定是否需要替换。如果找到了匹配的占位符,则根据占位符对应的值来进行替换。如果值不为空且非空字符串,则将占位符替换为对应的值;如果值为空或空字符串,则将占位符替换为空字符串。 请注意,上述代码中使用的占位符格式为`${placeholder}`,你可以根据实际情况修改为其他格式。 以上是一个基本示例,你可以根据自己的需求进行修改和扩展。同时,需要确保在项目中添加了Poi-tl的依赖库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值