word文档操作-doc转docx、合并多个docx
前言:
临时来了一条新的需求:多个doc文档进行合并。
在网上苦苦搜罗了很久才找到可用的文件(原文出处到不到了 所以暂时不能加链接地址了),现在记录下留给有需要的人。
一:doc转docx
所需jar包:链接: https://pan.baidu.com/s/1WQ33HDsON8lpFQKgLu8pCQ 提取码: n1xt
具体代码
public class Doc2Docx {
public static void main(String[] args) {
String docFile = "D:/files/dfa3cbb9-a0a0-497a-aa9f-d26cbee9a25b_linux.doc";
String docxFile = "D:/print/linux.docx";
doc2docx(docFile, docxFile);
}
/**
* doc转docx
* @param docFile 源文件
* @param docxFile 目标文件
*/
public static void doc2docx(String docFile, String docxFile) {
Document doc;
try {
String tempFile = docxFile.substring(0, docxFile.lastIndexOf(".")) + "_temp"
+ docxFile.substring(docxFile.lastIndexOf("."), docxFile.length());
doc = new Document(docFile);
doc.save(tempFile);
Map<String, String> map = new HashMap<String, String>();
map.put("Evaluation Only. Created with Aspose.Words. Copyright 2003-2018 Aspose Pty Ltd.", "");
DocxReplace.replaceAndGenerateWord(tempFile, docxFile, map);
// forceDelete(new File(tempFile));
} catch (Exception e1) {
log.error("doc 2 docx exception:{}",e1.getMessage());
}
}
}
public class DocxReplace {
// 返回Docx中需要替换的特殊字符,没有重复项
// 推荐传入正则表达式参数"\\$\\{[^{}]+\\}"
public ArrayList<String> getReplaceElementsInWord(String filePath,
String regex) {
String[] p = filePath.split("\\.");
if (p.length > 0) {// 判断文件有无扩展名
// 比较文件扩展名
if (p[p.length - 1].equalsIgnoreCase("doc")) {
ArrayList<String> al = new ArrayList<>();
File file = new File(filePath);
HWPFDocument document = null;
try {
InputStream is = new FileInputStream(file);
document = new HWPFDocument(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Range range = document.getRange();
String rangeText = range.text();
CharSequence cs = rangeText.subSequence(0, rangeText.length());
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(cs);
int startPosition = 0;
while (matcher.find(startPosition)) {
if (!al.contains(matcher.group())) {
al.add(matcher.group());
}
startPosition = matcher.end();
}
return al;
} else if (p[p.length - 1].equalsIgnoreCase("docx")) {
ArrayList<String> al = new ArrayList<>();
XWPFDocument document = null;
try {
document = new XWPFDocument(
POIXMLDocument.openPackage(filePath));
} catch (IOException e) {
e.printStackTrace();
}
// 遍历段落
Iterator<XWPFParagraph> itPara = document
.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
String paragraphString = paragraph.getText();
CharSequence cs = paragraphString.subSequence(0,
paragraphString.length());
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(cs);
int startPosition = 0;
while (matcher.find(startPosition)) {
if (!al.contains(matcher.group())) {
al.add(matcher.group());
}
startPosition = matcher.end();
}
}
// 遍历表
Iterator<XWPFTable> itTable = document.getTablesIterator();
while (itTable.hasNext()) {
XWPFTable table = (XWPFTable) itTable.next();
int rcount = table.getNumberOfRows();
for (int i = 0; i < rcount; i++) {
XWPFTableRow row = table.getRow(i);
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
String cellText = "";
cellText = cell.getText();
CharSequence cs = cellText.subSequence(0,
cellText.length());
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(cs);
int startPosition = 0;
while (matcher.find(startPosition)) {
if (!al.contains(matcher.group())) {
al.add(matcher.group());
}
startPosition = matcher.end();
}
}
}
}
return al;
} else {
return null;
}
} else {
return null;
}
}
// 替换word中需要替换的特殊字符
public static boolean replaceAndGenerateWord(String srcPath, String destPath, Map<String, String> map) {
String[] sp = srcPath.split("\\.");
String[] dp = destPath.split("\\.");
if ((sp.length > 0) && (dp.length > 0)) {// 判断文件有无扩展名
// 比较文件扩展名
if (sp[sp.length - 1].equalsIgnoreCase("docx")) {
try {
XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage(srcPath));
// 替换段落中的指定文字
Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
List<XWPFRun> runs = paragraph.getRuns();
for (int i = 0; i < runs.size(); i++) {
String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition());
for (Entry<String, String> entry : map.entrySet()) {
if(oneparaString.indexOf(entry.getKey())!=-1){
oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());
runs.get(i).setText(oneparaString, 0);
}
}
}
}
// 替换表格中的指定文字
Iterator<XWPFTable> itTable = document.getTablesIterator();
while (itTable.hasNext()) {
XWPFTable table = (XWPFTable) itTable.next();
int rcount = table.getNumberOfRows();
for (int i = 0; i < rcount; i++) {
XWPFTableRow row = table.getRow(i);
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
String cellTextString = cell.getText();
for (Entry<String, String> e : map.entrySet()) {
if (cellTextString.contains(e.getKey())) {
cellTextString = cellTextString.replace(e.getKey(),e.getValue());
cell.removeParagraph(0);
cell.setText(cellTextString);
cell.setColor(cell.getColor());
}
}
}
}
}
FileOutputStream outStream = null;
outStream = new FileOutputStream(destPath);
document.write(outStream);
outStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} else
// doc只能生成doc,如果生成docx会出错
if ((sp[sp.length - 1].equalsIgnoreCase("doc"))
&& (dp[dp.length - 1].equalsIgnoreCase("doc"))) {
HWPFDocument document = null;
try {
document = new HWPFDocument(new FileInputStream(srcPath));
Range range = document.getRange();
for (Entry<String, String> entry : map.entrySet()) {
range.replaceText(entry.getKey(), entry.getValue());
}
FileOutputStream outStream = null;
outStream = new FileOutputStream(destPath);
document.write(outStream);
outStream.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
} else {
return false;
}
}
}
二:合并多个docx
public class WordMergeUtil {
public static void main (String[] args) throws Exception {
File newFile = new File("D:\\wdpj\\t.docx");
List<File> srcfile = new ArrayList<>();
// File file1 = new File("D:\\wdpj\\函.docx");
// File file2 = new File("D:\\wdpj\\1.docx");
File file1 = new File("D:\\wdpj\\2.docx");
File file2 = new File("D:\\wdpj\\3.docx");
File file3 = new File("D:\\wdpj\\函.docx");
// srcfile.add(file2);
// srcfile.add(file1);
srcfile.add(file1);
srcfile.add(file2);
srcfile.add(file3);
try {
OutputStream dest = new FileOutputStream(newFile);
ArrayList<XWPFDocument> documentList = new ArrayList<>();
XWPFDocument doc = null;
for (int i = 0; i < srcfile.size(); i++) {
FileInputStream in = new FileInputStream(srcfile.get(i).getPath());
OPCPackage open = OPCPackage.open(in);
XWPFDocument document = new XWPFDocument(open);
documentList.add(document);
}
for (int i = 0; i < documentList.size(); i++) {
doc = documentList.get(0);
if(i != 0){
documentList.get(i).createParagraph().setPageBreak(true);
appendBody(doc,documentList.get(i));
}
}
// doc.createParagraph().setPageBreak(true);
doc.write(dest);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
XWPFParagraph p = src.createParagraph();
//设置分页符
p.setPageBreak(true);
CTBody src1Body = src.getDocument().getBody();
CTBody src2Body = append.getDocument().getBody();
List<XWPFPictureData> allPictures = append.getAllPictures();
// 记录图片合并前及合并后的ID
Map<String,String> map = new HashMap();
for (XWPFPictureData picture : allPictures) {
String before = append.getRelationId(picture);
//将原文档中的图片加入到目标文档中
String after = src.addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
map.put(before, after);
}
appendBody(src1Body, src2Body,map);
}
private static void appendBody(CTBody src, CTBody append,Map<String,String> map) throws Exception {
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = append.xmlText(optionsOuter);
String srcString = src.xmlText();
String prefix = srcString.substring(0,srcString.indexOf(">")+1);
String mainPart = srcString.substring(srcString.indexOf(">")+1,srcString.lastIndexOf("<"));
String sufix = srcString.substring( srcString.lastIndexOf("<") );
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
if (map != null && !map.isEmpty()) {
//对xml字符串中图片ID进行替换
for (Map.Entry<String, String> set : map.entrySet()) {
addPart = addPart.replace(set.getKey(), set.getValue());
}
}
//将两个文档的xml内容进行拼接
CTBody makeBody = CTBody.Factory.parse(prefix+mainPart+addPart+sufix);
src.set(makeBody);
}
word文档操作-doc转docx、合并多个docx的更多相关文章
- Word文档操作知识
Word文档操作知识 #持续更新 本次更新时间:2019-03-06 14:34 一.换行时字体空间过大 问题情景:当我们编写中文的文档时,中间插入了西方的字体或符号,在以它为行尾换行时: 会出现字体 ...
- word文档操作
1.如何把word文档修改的地方标记出来 : https://zhidao.baidu.com/question/73648149.html 2.word 的几种 视图:https://zhid ...
- poi导出word文档,doc和docx
maven <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency> <gro ...
- JAVA Asponse.Word Office 操作神器,借助 word 模板生成 word 文档,并转化为 pdf,png 等多种格式的文件
一,由于该 jar 包不是免费的, maven 仓库一般不会有,需要我们去官网下载并安装到本地 maven 仓库 1,用地址 https://www-evget-com/product/564 ...
- 利用POI操作不同版本号word文档中的图片以及创建word文档
我们都知道要想利用java对office操作最经常使用的技术就应该是POI了,在这里本人就不多说到底POI是什么和怎么用了. 先说本人遇到的问题,不同于利用POI去向word文档以及excel文档去写 ...
- JAVA Freemarker + Word 模板 生成 Word 文档 (普通的变量替换,数据的循环,表格数据的循环,以及图片的东替换)
1,最近有个需求,动态生成 Word 文当并供前端下载,网上找了一下,发现基本都是用 word 生成 xml 然后用模板替换变量的方式 1.1,这种方式虽然可行,但是生成的 xml 是在是太乱了,整理 ...
- word 文档导出 (freemaker+jacob)--java开发
工作中终于遇到了 需要导出word文旦的需求了.由于以前没有操作过,所以就先百度下了,基本上是:博客园,简书,CDSN,这几大机构的相关帖子比较多,然后花了2周时间 才初步弄懂. 学习顺序: 第一阶 ...
- C# 设置Word文档保护(加密、解密、权限设置)
对于一些重要的word文档,出于防止资料被他人查看,或者防止文档被修改的目的,我们在选择文档保护时可以选择文档打开添加密码或者设置文档操作权限等,在下面的文章中将介绍如何使用类库Free Spire. ...
- C#/VB.NET 给Word文档添加/撤销书签
在现代办公环境中,阅读或者编辑较长篇幅的Word文档时,想要在文档中某一处或者几处留下标记,方便日后查找.修改时,需要在相对应的文档位置插入书签.那对于开发者而言,在C#或者VB.NET语言环境中,如 ...
随机推荐
- 给spark submit main传递参数
https://www.jianshu.com/p/1d41174441b6 注意传递过去的默认是string,如果修改只能在代码中修改
- SQL Server如何正确的删除Windows认证用户
在SQL Server数据库中,有时候会建立一些Windows认证的账号(域账号),例如,我们公司习惯给开发人员和Support同事开通NT账号权限,如果有离职或负责事宜变更的话,那么要如何正确的删除 ...
- 原创【cocos2d-x】CCMenuItemToggle 在lua中的使用
说明:1,所使用的cocos2dx版本为2.1.3 ;09:48:05 2,本人仍是在学习中的小菜鸟,此博客只是为了记录我学习过程中的点滴,同时也希望同样lua开发的童鞋,一起交流: 3,本人whj0 ...
- golang中,new和make的区别
在golang中,make和new都是分配内存的,但是它们之间还是有些区别的,只有理解了它们之间的不同,才能在合适的场合使用. 简单来说,new只是分配内存,不初始化内存: 而make即分配又初始化内 ...
- Spring的常用注解
Spring框架主要包括IoC和AOP,这两大功能都可以使用注解进行配置. 开发环境:IntelliJ IDEA 2019.2.2Spring Boot版本:2.1.8新建一个名称为demo的Spri ...
- GitHub访问速度慢的一种优化方法
GitHub是一个面向开源及私有软件项目的托管平台,因为只支持Git 作为唯一的版本库格式进行托管,故名GitHub. 由于GitHub是一个国外网站,在国内访问速度如何呢? 我们通过浏览器访问下ht ...
- Flutter中通过https post Json接收Json
Flutter 已然成为炙手可热前端框架.若问跨平台到底有多香,自然是要多香有多香.今天我就分享这些天研究Flutter http连接和json格式转换的内容,小弟对Flutter也是小白一名,如有错 ...
- linux 的swap、swappiness及kswapd原理【转】
本文讨论的 swap基于Linux4.4内核代码 .Linux内存管理是一套非常复杂的系统,而swap只是其中一个很小的处理逻辑. 希望本文能让读者了解Linux对swap的使用大概是什么样子.阅读完 ...
- raid组合优缺点介绍和创建LVM实验个人笔记
一.RAID组合介绍 RAID模式优缺点的简要介绍 1.raid 0 模式 优点:在RAID 0状态下,存储数据被分割成两部分,分别存储在两块硬盘上,此时移动硬盘的理论存储速度是单块硬盘的2倍,实际容 ...
- 面向对象OPP
在此之前学习的编程方式均称为面向过程,过程类似于函数,只能执行,没有返回值 面向过程和面向对象 面向过程-->怎么做? 面向对象-->谁来做? 相比函数,面向对象 是更大的封装,根据职 ...