一、简介
主要使用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;
}
}
如果有问题,可以留言。完整代码由于项目原因,无法放出,还请谅解。留言看到会及时回复的!