docx4j官网:docx4j (docx4java.org)
案例:【docx4j】docx4j操作docx,实现替换内容、转换pdf、html等操作 - QiaoZhi - 博客园 (cnblogs.com)
docx4j文档案例: GitHub - plutext/docx4j: JAXB-based Java library for Word docx, Powerpoint pptx, and Excel xlsx files
第一种方式:
import org.apache.commons.io.IOUtils;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.WordprocessingML.AlternativeFormatInputPart;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.CTAltChunk;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MargeDoc {
public void mergeDocx(List<String> list, String path) {
List<InputStream> inList = new ArrayList<InputStream>();
for (int i = 0; i < list.size(); i++){
try {
inList.add(new FileInputStream(list.get(i)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
try {
InputStream inputStream = mergeDocx(inList);
saveTemplate(inputStream, path);
} catch (Docx4JException | IOException e) {
e.printStackTrace();
}
}
public InputStream mergeDocx(final List<InputStream> streams) throws Docx4JException, IOException {
WordprocessingMLPackage target = null;
final File generated = File.createTempFile("generated", ".docx");
int chunkId = 0;
Iterator<InputStream> it = streams.iterator();
while (it.hasNext()) {
InputStream is = it.next();
if (is != null) {
if (target == null) {
OutputStream os = new FileOutputStream(generated);
os.write(IOUtils.toByteArray(is));
os.close();
target = WordprocessingMLPackage.load(generated);
} else {
insertDocx(target.getMainDocumentPart(), IOUtils.toByteArray(is), chunkId++);
}
}
}
if (target != null) {
target.save(generated);
return new FileInputStream(generated);
} else {
return null;
}
}
/**
* 插入文档
* @param main
* @param bytes
* @param chunkId
*/
private void insertDocx(MainDocumentPart main, byte[] bytes, int chunkId) {
try {
AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(
new PartName("/part" + chunkId + ".docx"));
afiPart.setBinaryData(bytes);
Relationship altChunkRel = main.addTargetPart(afiPart);
CTAltChunk chunk = Context.getWmlObjectFactory().createCTAltChunk();
chunk.setId(altChunkRel.getId());
main.addObject(chunk);
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveTemplate(InputStream fis, String toDocPath) {
FileOutputStream fos;
int bytesum = 0;
int byteread = 0;
try {
fos = new FileOutputStream(toDocPath);
byte[] buffer = new byte[1444];
while ((byteread = fis.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
fos.write(buffer, 0, byteread);
}
fis.close();
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Docx4JException, IOException {
MargeDoc wordUtil = new MargeDoc();
String template = "C:/Users/admin/Desktop/a";
List<String> list = new ArrayList<String>();
list.add(template + "/test1.docx");
list.add(template + "/test2.docx");
wordUtil.mergeDocx(list, template + "/out.docx");
}
}
用到的依赖
第二种方式:
public static void mergeWord(String outputPath, List<InputStream> list) throws Exception{
List<WordprocessingMLPackage> wmlList = new ArrayList<>();
for (InputStream inputStream : list) {
wmlList.add(WordprocessingMLPackage.load(inputStream));
}
mergeWord(wmlList, outputPath);
}
/**
* 合并文件
* @param list
* @throws Exception
*/
public static void mergeWord(List<WordprocessingMLPackage> list, String outputPath) throws Exception{
List<BlockRange> blockRanges = new ArrayList<BlockRange>();
HashMap<String, Object> result = new HashMap<>();
if (list != null && !list.isEmpty()) {
for (int i = 0; i < list.size(); i++) {
WordprocessingMLPackage wordMLPackage = list.get(i);
BlockRange block = new BlockRange(wordMLPackage);
blockRanges.add(block);
if (i == 2) {
//是否重新开始页码
block.setRestartPageNumbering(true);
} else {
block.setRestartPageNumbering(false);
}
// block.setStyleHandler(BlockRange.StyleHandler.USE_EARLIER);
block.setNumberingHandler(BlockRange.NumberingHandler.ADD_NEW_LIST);
block.setHeaderBehaviour(BlockRange.HfBehaviour.DEFAULT);
block.setFooterBehaviour(BlockRange.HfBehaviour.DEFAULT);
//设置分节符(下一页)
block.setSectionBreakBefore(BlockRange.SectionBreakBefore.NEXT_PAGE);
}
// Perform the actual merge
DocumentBuilder documentBuilder = new DocumentBuilder();
WordprocessingMLPackage output = documentBuilder.buildOpenDocument(blockRanges);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
output.save(outputStream);
OutputStream os = new FileOutputStream(new File(outputPath));
outputStream.writeTo(os);
os.close();
outputStream.close();
}
}
用到的依赖: