Java将编辑器的内容导出成为word文件

添加依赖 

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.17</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.14</version>
</dependency>

 网页导出成word文档的默认视图方式问题

一般保存后的word文档默认是“Web版式视图”打开,这样会给客户的感觉不是真正的word文档,必须实现打开就是“页面视图”

  1. 修改<html>标签:

首先把原来的html标签中要加入模板:

<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">

2.在<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]-->

这样就可以把保存的word文档默认为“页面视图”打开

3、直接上代码

package com.shucha.projhigh.web.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.controller.BaseController;
import com.shucha.projhigh.biz.model.InspectedExportReview;
import com.shucha.projhigh.biz.model.InspectedTemplate;
import com.shucha.projhigh.biz.service.InspectedExportReviewService;
import com.shucha.projhigh.biz.service.InspectedTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.net.URLEncoder;

/**
 * @author tqf
 * @Description
 * @Version 1.0
 * @since 2022-02-24 15:35
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/export")
@Api(tags = "编辑器内容相关接口")
public class ExportWordController extends BaseController {
    @Autowired
    private InspectedTemplateService inspectedTemplateService;
    @Autowired
    private InspectedExportReviewService reviewService;

    @GetMapping("/upload")
    @ApiOperation(value = "下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "type", value = "类型(0-专家评审,1-大数据中心评审)"),
            @ApiImplicitParam(dataType = "Long", name = "id", value = "项目ID")
    })
    public void exportWord(HttpServletRequest request, HttpServletResponse response, Integer type, Long id) {
        try {
            Assert.isNull(type,"类型不能为空!");
            Assert.isNull(id,"项目ID不能为空!");
            // 查询模板内容
            InspectedTemplate inspectedTemplate = inspectedTemplateService.getOne(Wrappers.<InspectedTemplate>lambdaQuery()
                    .orderByDesc(), false);
            // 查询评审内容
            InspectedExportReview review  = reviewService.getOne(Wrappers.<InspectedExportReview>lambdaQuery()
                    .eq(InspectedExportReview::getProjectId, id)
                    .eq(InspectedExportReview::getType, type), false);
            //word内容
            String content = "";
            if(review != null && StringUtil.isNotBlank(review.getContent())) {
                content = review.getContent();
            } else {
                if(inspectedTemplate != null) {
                    // 根据评审类型获取不同的模板内容
                    if(type.equals(0)) {
                        content = inspectedTemplate.getContent();
                    } else {
                        content = inspectedTemplate.getExportContent();
                    }
                }
            }
            // 给内容添加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>";
            byte b[] = content.getBytes("GBK");  //这里是必须要设置编码的,不然导出中文就会乱码。
            ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中

            /*
             * 关键地方
             * 生成word格式 */
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
            //输出文件
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode("评审意见书", "UTF-8")+".doc");
            ServletOutputStream ostream = response.getOutputStream();
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.close();
            poifs.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

 

4、下面的方式是可以把base64的图片也导出到word文件里面

项目需要依赖 spire.doc.free-2.7.3.jar,但是无法从maven仓库下载到,现在附上jar包下载地址:

spire.doc.free-2.7.3.jar包下载icon-default.png?t=M1L8https://download.csdn.net/download/tanqingfu1/83200053

package com.shucha.datasupervision.web.controller;

import com.sdy.mvc.controller.BaseController;
import com.shucha.datasupervision.biz.utils.JfreeChartUtil;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author tqf
 * @Description
 * @Version 1.0
 * @since 2022-03-03 14:33
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/test")
public class TetsController extends BaseController {

    @GetMapping("/upload")
    public  void exportWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            String content = "<p style=\"text-align: center;\"><span style=\"font-size: 36px;\"><strong><span style=\"color: rgb(255, 0, 0); text-decoration: underline;\">乐清市大数据管理中心</span></strong></span></p><p style=\"text-align: center;\"><span style=\"color: rgb(0, 0, 0); text-decoration: none; font-size: 24px;\">乐清市XXX项目方案论证意见</span></p><p>&nbsp; 2022年xx月xx日,乐清市人民政府办公室(大数据管理中心)会同财政局、教育局等部门,组织专家在乐清市行政管理中心主楼5楼2号会议室,召开了“乐清市东山小学智能化工程项目”(以下简称项目)方案评审会,专家组听取了项目建设单位的介绍,审阅了有关资料,并进行了质询。经讨论,形成论证意见如下:</p><p><br/></p><p>&nbsp; 专家签名:<br/></p>";
            content = content + "<img data-v-5bf6aa59=\"\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADgAAAA4CAYAAACohjseAAALbklEQVRogcWbCXQURRrHf9OTmclNEiCHQALILQuGU2EBUQ4PTlFXl1WRS7mUVVnEBUQQDzwWz1XAlRVQdOUSEF2ExcV9IpeAHEkIV4whhNwJyVw9va8m3UmGXN2T4fl/Ly/d1VVf1b/qq6qv6vvGZAmLxygkSWLEncOYNX0SnTq2v7q0GegJDAC6ASJDS6AJEKnmKQaKgEzgNHAM2AscAmRNUFlZOWs/+RcffPgxOTm5htspYJhg/5v7sPi5uXRof331ZBswBrgPuE0l4w8E6V3A58BmwCFkOBwOVqxaw1vvrcRud1w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hL12K5CTVOPbvNJE+Fe2Wmf6qkatQ5RVxcXzbc+v6Y7wyanU1bu0VVYV8SvQEmpk1Vf5JJV3IlBvUNcFlOhsKtWqCcR4aWs8zi+dRdkZvm6wNrFp5EYX2//5KsBSfdjsmzbm9bLdeukPPbsz9fVXg2GL0DWbD5H4vAClm/uxRW5rThDLlDjSYXttFGNqPdBh5a+NmtkZBjxMbWqZ7EqQ8hKUAhZsP9s77x+U2MZNS2FwhLj9z1+/aygsrAJHrknianjbLSPPYWkeE2k6j8r6K6GZLb88ujMmNUffR3WLDbOtXhOi9J4y+eCoVj+xFak/azgoJi2Ra72fLUvmhffv0Bmto85ZgzA/wG84usfTxKpZwAAAABJRU5ErkJggg==\" alt=\"\" class=\"head\">";
            //新建Document对象
            Document document = new Document();
            //添加section
            Section sec = document.addSection();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //添加段落并写入HTML文本
            sec.addParagraph().appendHTML(content);
            document.saveToStream(os, FileFormat.Docx);

            InputStream input = new ByteArrayInputStream(os.toByteArray());

            //输出文件
            request.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    URLEncoder.encode("123", "utf-8") + ".docx");

            ServletOutputStream ostream = response.getOutputStream();
            int len =-1;
            byte []by = new byte[1024];
            while((len = input.read(by))!=-1) {
                ostream.write(by,0,len);
            }
            ostream.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

导出的文件效果图如下:


参考文章地址https://www.cnblogs.com/jcz1206/p/3517223.html?ivk_sa=1024320u

参考实现代码文章地址https://blog.csdn.net/weixin_42259631/article/details/80996198

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码奴生来只知道前进~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值