这是mian函数方法
System.out.println("shenqingshu");
List<String> mmList = new ArrayList<String>();
mmList.add("D:\\申请书\\2\\1.docx");
mmList.add("D:\\申请书\\2\\2.docx");
mmList.add("D:\\申请书\\2\\3.docx");
mmList.add("D:\\申请书\\2\\4.docx");
mmList.add("D:\\申请书\\2\\5.docx");
/*mmList.add("D:\\申请书\\2\\1.docx");
mmList.add("D:\\申请书\\2\\2.docx");*/
DocxMergeUtil mmDocxMergeUtil = new DocxMergeUtil();
mmDocxMergeUtil.merge(mmList,"D:\\123123.docx");
下面的是具体合并的方法
public static void merge(List<String> list, String path) throws Exception {
List<InputStream> inList = new ArrayList<InputStream>();
for (int i = 0; i < list.size(); i++){
inList.add(new FileInputStream(list.get(i)));
}
InputStream inputStream = mergeDocx(inList);
saveTemplate(inputStream, path);
}
public static InputStream mergeDocx(final List<InputStream> streams){
try {
WordprocessingMLPackage target = null;
//创建临时Docx文件
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;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* * 插入文档 * @param main * @param bytes * @param chunkId
*/
public static void insertDocx(MainDocumentPart main, byte[] bytes, int chunkId) {
try {
AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(
new PartName("/part" + chunkId + ".docx"));
// afiPart.setContentType(new ContentType(CONTENT_TYPE));
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();
}
}
/**
* * 输出文件 * @param fis * @param toDocPath
*/
public static 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();
}
}
求解,如何插入分页符,使每个文档都是从下一页开始,而不是跟着上一个文档空余的地方。