java导出word

本文档介绍了如何使用Spire.Doc库在Java中创建Word模板并填充数据,包括普通信息、List类型表格信息和富文本信息。通过创建模板并在特定位置标记,然后读取模板替换内容,实现了从网页数据到Word报告的自动化导出。
摘要由CSDN通过智能技术生成

一、简介

主要使用spire.doc实现申报表的导出,只能在这里贴出部分表格。下面两张图分别为:网页图和word截图。导出的信息包含简单的表格信息、List类型信息和富文本信息。

(1)普通信息
在这里插入图片描述
在这里插入图片描述
(2)List类型表格信息
在这里插入图片描述
(3)富文本信息

在这里插入图片描述
在这里插入图片描述

二、实现过程

(1)创建模板

此步骤主要使用一个特殊的字符来标明位置,方便后续替换。以下为三种类型信息的模板设置。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
(2)创建项目

1. 依赖

	<dependency>
		<groupId>e-iceblue</groupId>
		<artifactId>spire.doc.free</artifactId>
		<version>2.7.3</version>
	</dependency>

如果依赖无法正常导入的话,请下载相关的jar包,并且采用导入本地jar包的方式
本地jar包导入方式详情可见: 本地jar包导入方法

2. 工具类说明(项目原因,无法放出完整工具类,在这里会尽可能详细描述)

**
参数说明:
	template:word模板所在路径,类似 C:\\Users\\DELL\\Desktop\\证书信息统计表.doc
	outFile:  文件最终保存路径
	TjYouthWord :这是我的实体类,其中包含了基本信息,List数据和富文本数据(其实也是String)
	uploadPath: 文件保存路径,类似 C:\\upload,此处的主要作用为修正上传申报的个人照片的保存路径
代码说明:
	读取文中段落,找到要替换的位置 table_introduce,appendHtml作用为写入富文本数据,getRichData为获取完整富文本数据方法。
            for (int j = 0; j < section.getParagraphs().getCount(); j++) {
                Paragraph paragraph = section.getParagraphs().get(j);
                if (paragraph.getText().contains("table_introduce")){
                    paragraph.setText("");
                    paragraph.appendHTML(getRichData(tjYouthWord.getIntroduce(),uploadPath));
                    break;
                }
            }
    读取表格List数据:找到  // 第二种数据,表格类型  注释处
    替换个人照片:路径替换为照片路径就可以
            if(obj instanceof DocPicture){
                 if (isFirstPhoto) {
                     // 近期免冠2寸照片
                     DocPicture pic = (DocPicture)obj;
                     float height = pic.getHeight();
                     float width = pic.getWidth();
                     File file = new File(appPhoto);
                     if (file.exists()){
                         pic.loadImage(appPhoto);
                         pic.setHeight(height);
                         pic.setWidth(width);
                         isFirstPhoto = false;
                     }
                 }
             }
     替换富文本信息:上面已经叙述过,找到注释, // 十、其他重要成果及业绩、贡献		      	        

**
package cn.tj.util.table;

import cn.tj.dto.tjYouth.TjYouthWord;
import cn.tj.entity.*;
import com.google.inject.internal.cglib.reflect.$FastMember;
import com.spire.doc.*;
import com.spire.doc.collections.CellCollection;
import com.spire.doc.collections.DocumentObjectCollection;
import com.spire.doc.collections.SectionCollection;
import com.spire.doc.collections.TableCollection;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;
import com.spire.doc.fields.DocPicture;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.logging.SimpleFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 表1
 *
 * @author zjl
 * @date 2021/04/15
 */
@Component
public class Table1Utils {

    /**
     * 导出word
     * @param template   加载的模板路径
     * @param outFile    输出文件路径
     */
    public void export(String template, String outFile, TjYouthWord tjYouthWord,String uploadPath) {
        System.out.println("开始导出word"+"模板为:"+template);
        // 加载模板文档.......................................
        Document document = new Document(template);
        // 读取模板文档.......................................
        // 获取文档中的所有节
        SectionCollection sections = document.getSections();
        // 替换文档中指定数据
        // 基础信息
        document.replace("app_sex", NullToEmpty(tjYouth.getAppSex()) , false, true);
        // 照片
        String appPhoto = tjYouth.getAppPhoto()==null?"":tjYouth.getAppPhoto();
        appPhoto = uploadPath + appPhoto;
        boolean isFirstPhoto = true;
        // 指替换一次填表说明
        boolean isIntroduce = true;
        // 遍历节
        for (int i = 0; i < sections.getCount(); i++) {
            Section section = sections.get(i);
            // 遍历该节所有段落,替换填表说明
/*            if (isIntroduce){
                for (int j = 0; j < section.getParagraphs().getCount(); j++) {
                    Paragraph paragraph = section.getParagraphs().get(j);
                    if (paragraph.getText().contains("table_introduce")){
                        paragraph.setText("");
                        paragraph.appendHTML(getRichData(tjYouthWord.getIntroduce(),uploadPath));
                        isIntroduce = false;
                        break;
                    }
                }
            }*/
            // 遍历该节中的所有表格
            TableCollection tables = section.getTables();
            for (int j = 0; j < tables.getCount(); j++) {
                Table table = tables.get(j);
                // 遍历表格信息
                for (int m = 0; m < table.getRows().getCount(); m++) {
                    CellCollection cells = table.getRows().get(m).getCells();
                    // 对应m行n列的单元格
                    for (int n = 0; n < cells.getCount(); n++) {
                        TableCell tableCell = cells.get(n);
                        for (int l = 0; l < tableCell.getParagraphs().getCount(); l++) {
                            DocumentObjectCollection childObjects = tableCell.getParagraphs().get(l).getChildObjects();
                            for (Object o:(Iterable) childObjects) {
                                DocumentObject obj = (DocumentObject) o;
                                //使用新图片替换文档中的现有图片
                                if(obj instanceof DocPicture){
                                    if (isFirstPhoto) {
                                        // 近期免冠2寸照片
                                        DocPicture pic = (DocPicture)obj;
                                        float height = pic.getHeight();
                                        float width = pic.getWidth();
                                        File file = new File(appPhoto);
                                        if (file.exists()){
                                            pic.loadImage(appPhoto);
                                            pic.setHeight(height);
                                            pic.setWidth(width);
                                            isFirstPhoto = false;
                                        }
                                    }
                                }
                            }

                            // 第二种数据,表格类型
                            if (tableCell.getParagraphs().get(l).getText().equals("book")){
                                List<TjYouthEdu> tjYouthEdus = tjYouthWord.getTjYouthEdus();
                                if (tjYouthEdus != null && !tjYouthEdus.isEmpty()) {
                                    int startRow = 1;
                                    for (int k = 0; k < tjYouthEdus.size(); k++) {
                                        TjYouthEdu edu = tjYouthEdus.get(k);
                                        if (edu.getEduDateStart() == null && edu.getEduDateEnd() == null){
                                            table.get(startRow,0).getParagraphs().get(0).setText("");
                                        }else{
                                            table.get(startRow,0).getParagraphs().get(0).setText(this.DateToYM(edu.getEduDateStart()) +"至" +this.DateToYM(edu.getEduDateEnd()));
                                        }
                                        table.get(startRow,1).getParagraphs().get(0).setText(NullToEmpty(edu.getEduSchool())+"/"+NullToEmpty(edu.getEduInstitute()));
                                        table.get(startRow,2).getParagraphs().get(0).setText((NullToEmpty(edu.getEduMajor())));
                                        table.get(startRow,3).getParagraphs().get(0).setText((NullToEmpty(edu.getEduDegree())));
                                        startRow += 1;
                                    }
                                }else{
                                    // 清空表中第一行数据
                                    table.get(1,0).getParagraphs().get(0).setText("");
                                }
                            }
                         
                            // 十、其他重要成果及业绩、贡献
                            if (tableCell.getParagraphs().get(l).getText().equals("tenMainAchieve")){
                                if (tjYouth.getAppAchievement()!=null) {
                                    tableCell.getParagraphs().get(l).setText("");
                                    tableCell.getParagraphs().get(l).appendHTML(getRichData(tjYouth.getAppAchievement(),uploadPath));
                                    // 文档中默认字体为仿宋小三,此处改为宋体小四
                                    ParagraphStyle style = new ParagraphStyle(document);
                                    String titleStyle = UUID.randomUUID().toString().replace("-","").substring(0,8);
                                    style.setName(titleStyle);
                                    style.getCharacterFormat().setBold(true);
                                    style.getCharacterFormat().setTextColor(Color.BLACK);
                                    style.getCharacterFormat().setFontName("宋体");
                                    style.getCharacterFormat().setFontSize(12f);
                                    style.getCharacterFormat().setBold(false);
                                    document.getStyles().add(style);
                                    tableCell.getParagraphs().get(l).applyStyle(titleStyle);
                                }else{
                                    tableCell.getParagraphs().get(l).setText("");
                                }
                            }
                        }
                    }
                }
            }
        }


        //保存结果文档
        document.saveToFile(outFile, FileFormat.Docx_2013);

    }

    /**
     * 空指针处理
     * @param s
     * @return
     */
    private String NullToEmpty(String s) {
        if (s == null){
            return "";
        }
        return s;
    }

    /**
     * 将Date转化为字符串
     * @param date
     * @return
     */
    private String DateToString(Date date) {
        if (date == null){
            return "";
        }
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

    /**
     * 将Date转化为字符串 年月
     * @param date
     * @return
     */
    private String DateToYM(Date date) {
        if (date == null){
//            return "";
            return new SimpleDateFormat("yyyy-MM").format(new Date());
        }
        return new SimpleDateFormat("yyyy-MM").format(date);
    }

    /**
     * 文件地址和日期时间比对,判断是否需要更新导出的word文件
     * @param file
     * @param date
     * @return
     */
    public boolean isNeedUpdateWord(String file,Date date){
        File f = new File(file);
        System.out.println("文件地址"+file);
        if (!f.exists()){
            return true;
        }
        Calendar cal = Calendar.getInstance();
        long time = f.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cal.setTimeInMillis(time);
        // 文件最后修改时间
        String fileTime = formatter.format(cal.getTime());
        System.out.println(fileTime);
        // 数据更新时间
        String dataTime = formatter.format(date);
        System.out.println(dataTime);
        if (fileTime.compareTo(dataTime) < 0){
//            System.out.println("文件最后修改时间早于数据更新");
            return true;
        }
        return false;
    }

    /**
     * 解析富文本数据
     * @param richData
     * @return
     */
    public String getRichData(String richData,String uploadPath){
        String header = "<html><body>";
        String footer = "</body></html>";
        if (richData == null){
            return header+footer;
        }
        String richText = "";
        // 处理富文本中的图片数据,修正图片存储位置
        if(richData.contains("<img")) {
            Matcher matcher1 = Pattern.compile("<img[\\s\\S]src=\"([\\s\\S]*?)\"[\\s\\S]*?/>").matcher(richData);
            while (matcher1.find()) {
                String temp=matcher1.group(1);
                richData= Pattern.compile(temp).matcher(richData).replaceAll(uploadPath+temp);
            }
        }
        richText = header + richData + footer;
        return richText;
    }

}

如果有问题,可以留言。完整代码由于项目原因,无法放出,还请谅解。留言看到会及时回复的!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值