国内有个免费的jar(Free Spire.Doc for Java),可用来合并Word文档,分两种合并方法:1.合并的内容新起一页;2.合并的内容承接上文段落。1.新起一页合并 import com.spire.doc.Document;import com.spire.doc.FileFormat;public class MergeWordDocument { public static void main(String[] args...
如何通过java将多个word文档合成一个wor
Java可以使用这个开源框架,对word进行读取合并等操作,Apache POI是一个开源的利用Java读写Excel、WORD等微软OLE2组件文档的项目。最新的3.5版本有很多改进,加入了对采用OOXML格式的Office 2007支持,如xlsx、docx、pptx文档。 示例如下:
import org.apache.poi.POITextExtractor; import org.apache.poi.hwpf.extractor.WordExtractor; //得到.doc文件提取器 org.apache.poi.hwpf.extractor.WordExtractor doc = new WordExtractor(new FileInputStream(filePath)); //提取.doc正文文本 String text = doc.getText(); //提取.doc批注 String[] comments = doc. getCommentsText(); 2007 import org.apache.poi.POITextExtractor; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFComment; import org.apache.poi.xwpf.usermodel.XWPFDocument; //得到.docx文件提取器 org.apache.poi.xwpf.extractor.XWPFWordExtractor docx = new XWPFWordExtractor(POIXMLDocument.openPackage(filePath)); //提取.docx正文文本 String text = docx.getText(); //提取.docx批注 org.apache.poi.xwpf.usermodel.XWPFComment[] comments = docx.getDocument()).getComments(); for(XWPFComment comment:comments){ comment.getId();//提取批注Id comment.getAuthor();//提取批注修改人 comment.getText();//提取批注内容 }2018-11-05
国内有个免费的jar(Free Spire.Doc for Java),可用来合并Word文档,分两种合并方法:1.合并的内容新起一页;2.合并的内容承接上文段落。
1.新起一页合并
import com.spire.doc.Document;import com.spire.doc.FileFormat;public class MergeWordDocument { public static void main(String[] args){ //获取第一个文档的路径 String filePath1 = "merge1.docx"; //获取第二个文档的路径 String filePath2 = "merge2.docx"; //加载第一个文档 Document document = new Document(filePath1); //使用insertTextFromFile方法将第二个文档的内容插入到第一个文档 document.insertTextFromFile(filePath2, FileFormat.Docx_2013); //保存文档 document.saveToFile("Output.docx", FileFormat.Docx_2013); }}2.承接上文段落合并
import com.spire.doc.Document;import com.spire.doc.DocumentObject;import com.spire.doc.FileFormat;import com.spire.doc.Section;public class MergeWordDocument { public static void main(String[] args){ //获取第一个文档的路径 String filePath1 = "merge1.docx"; //获取第二个文档的路径 String filePath2 = "merge2.docx"; //加载第一个文档 Document document1 = new Document(filePath1); //加载第二个文档 Document document2 = new Document(filePath2); //获取第一个文档的最后一个section Section lastSection = document1.getLastSection(); //将第二个文档的段落作为新的段落添加到第一个文档的最后一个section for (Section section:(Iterable <Section>)document2.getSections()) { for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects() ) { lastSection.getBody().getChildObjects().add(obj.deepClone()); } } //保存文档 document1.saveToFile("Output.docx", FileFormat.Docx_2013); }}可参考原文。
2019-06-27