Java word файлы в один

Современная Java библиотека позволяет Java разработчикам легко конвертировать Word файлы. Наш движок Word конверсии анализирует исходные Word файлы, а затем экспортирует объединенный контент в требуемый формат.

Конверсия Word может стать непростой задачей, но только если у вас нет профессионального инструмента для выполнения такой работы. Используйте Java библиотеку для преобразования Word с максимальной гибкостью и скоростью. Запустите онлайн-демонстрацию и проверьте высочайшее качество Word прямо в веб-браузере. Word Conversion API поддерживает множество полезных опций.

Объединить Word используя Java

Расширьте возможности Word формата с помощью Aspose.Words for Java. Это простой способ объединить Word файлы на базе Java библиотеки, которая обрабатывает все низкоуровневые детали.

Объедините Word и сохраните результат как один файл. Если вы разрабатываете Java код, это окажется намного проще, чем может показаться изначально. См. пример на Java, который выполняет преобразование группы Word документов, объединяя их в единое целое:

Java для объединения Word файлов

Мы размещаем наши пакеты Java в репозиториях Maven. ‘Aspose.Words для Java’ — это обычный JAR файл, содержащий байт-код. Следуйте пошаговым инструкциям по его установке в среде разработчика Java.

Системные Требования

Поддерживаются Java SE 7 и более поздние версии Java. Мы также предоставляем отдельный пакет для Java SE 6 на случай, если вам придется использовать эту устаревшую JRE.

Наша библиотека Java является кроссплатформенной и работает во всех операционных системах с JVM, включая Microsoft Windows, Linux, macOS, Android и iOS.

Для получения информации о дополнительных зависимостях пакетов, таких как JogAmp JOGL, Harfbuzz шрифтов Java Advanced Imaging JAI, обратитесь к документации по продукту.

When you have a massive Word document to deal with, you can always split the document into small pieces and distribute them to multiple colleagues. After everyone has finished editing, all you need to do is merge these documents into a single document. To do so, you can effectively shorten the time limit for the project. In this article, I am going to introduce how to split or merge Word documents by using Spire.Doc for Java.

Add Spire.Doc.jar as dependency

If you create a Maven project, you can easily import the jar in your application using the following configurations. For non-Maven projects, please download the jar file from this link and manually add it as a dependency in your applicaition. 

  1. <repositories>  
  2.     <repository>  
  3.         <id>com.e-iceblue</id>  
  4.         <name>e-iceblue</name>  
  5.         <url>http:  
  6.     </repository>  
  7. </repositories>  
  8. <dependencies>  
  9.     <dependency>  
  10.         <groupId> e-iceblue </groupId>  
  11.         <artifactId>spire.doc</artifactId>  
  12.         <version>3.8.8</version>  
  13.     </dependency>  
  14. </dependencies>  

Example 1. Split document by section break

Spire.Doc provides the Document.getSectionsmethod, allowing programmers to easily access all sections within a document. Loop through these sections, get the specific one, and add its clone to a new document. The above steps will produce a sub-document.

Before you use this method to split document, make sure your document has multiple sections. Otherwise, it won’t work. In addition, Spire also supports splitting document by page break. If you’re interested, try it yourself.

  1. import com.spire.doc.Document;  
  2. public class SplitWordBySection {  
  3.     public static void main(String[] args) {  
  4.           
  5.         Document document = new Document();  
  6.           
  7.         document.loadFromFile(«C:\Users\Administrator\Desktop\sections.docx»);  
  8.           
  9.         Document newWord;  
  10.           
  11.         for (int i = 0; i < document.getSections().getCount(); i++) {  
  12.               
  13.             newWord = new Document();  
  14.               
  15.             newWord.getSections().add(document.getSections().get(i).deepClone());  
  16.               
  17.             newWord.saveToFile(String.format(«C:\Users\Administrator\Desktop\Output\result-%d.docx», i));  
  18.         }  
  19.     }  
  20. }  

Output

How To Split Or Merge Word Documents In Java

Example 2. Merge documents by inserting content into a new page

When you merge one document into another, you may want the content to be added to a new page instead of the last paragraph of the parent document. The Document.insertTextFromFile method allows you to accomplish this job easily.

  1. import com.spire.doc.Document;  
  2. import com.spire.doc.FileFormat;  
  3. public class MergeDocuments {  
  4.     public static void main(String[] args) throws Exception {  
  5.           
  6.         String[] filePaths = new String[] {  
  7.             «C:\Users\Administrator\Desktop\Documents\sample_1.docx»,  
  8.             «C:\Users\Administrator\Desktop\Documents\sample_2.docx»,  
  9.             «C:\Users\Administrator\Desktop\Documents\sample_3.docx»  
  10.         };  
  11.           
  12.         Document document = new Document(filePaths[0]);  
  13.           
  14.         for (int i = 1; i < filePaths.length; i++) {  
  15.               
  16.             document.insertTextFromFile(filePaths[i], FileFormat.Docx_2013);  
  17.         }  
  18.           
  19.         document.saveToFile(«C:\Users\Administrator\Desktop\MergedDocument.docx», FileFormat.Docx_2013);  
  20.     }  
  21. }  

Output

How To Split Or Merge Word Documents In Java

Example 3. Merge documents by inserting content behind the last paragraph

Apart from inserting content to a new page, you can insert content right behind the last paragraph of the previous document, so that the merged document appears to be continuous in content.

In the example 1,we already know how to access sections of a document. Under section, there is a more detailed division, which is child object. What we need to do is to get all the child objects of the current document and add them to the last section of the parent document. Remember to update the lastSection object dynamically, because each time we merge one document into the parent document, the lastSection changes. 

  1. import com.spire.doc.Document;  
  2. import com.spire.doc.DocumentObject;  
  3. import com.spire.doc.FileFormat;  
  4. import com.spire.doc.Section;  
  5. public class MergeDocuments {  
  6.     public static void main(String[] args) throws Exception {  
  7.           
  8.         String[] filePaths = new String[] {  
  9.             «C:\Users\Administrator\Desktop\sample_1.docx»,  
  10.             «C:\Users\Administrator\Desktop\sample_2.docx»,  
  11.             «C:\Users\Administrator\Desktop\sample_3.docx»  
  12.         };  
  13.           
  14.         Document firstDocument = new Document(filePaths[0]);  
  15.           
  16.         Section lastSection = firstDocument.getLastSection();  
  17.           
  18.         Document otherDocument;  
  19.           
  20.         for (int i = 1; i < filePaths.length; i++) {  
  21.               
  22.             otherDocument = new Document(filePaths[i]);  
  23.               
  24.             for (Object section: otherDocument.getSections()) {  
  25.                   
  26.                 for (Object childObj: ((Section) section).getBody().getChildObjects()) {  
  27.                       
  28.                     lastSection.getBody().getChildObjects().add(((DocumentObject) childObj).deepClone());  
  29.                 }  
  30.             }  
  31.               
  32.             lastSection = lastSection.getDocument().getLastSection();  
  33.         }  
  34.           
  35.         firstDocument.saveToFile(«C:\Users\Administrator\Desktop\MergedDocument.docx», FileFormat.Docx_2013);  
  36.     }  
  37. }  

Output

How To Split Or Merge Word Documents In Java

Thank you for taking the time to read this article. Happy coding!

Sometimes we need to merge several related Word documents to make a more complete one. To merge documents with MS Word, you need to manually copy and paste contents or import contents from other documents, which can be tedious. Luckily, Spire.Doc for Java provides 2 easy ways to merge Word documents by programming. This article will show the detailed steps to merge Word documents.

  • Merge Documents by Inserting the Entire File
  • Merge Documents by Cloning Contents

Install Spire.Doc for Java

First, you’re required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project’s pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>11.3.11</version>
    </dependency>
</dependencies>
    

Merge Documents by Inserting the Entire File

The method Document.insertTextFromFile() provided by Spire.Doc allows merging Word documents by inserting other documents entirely into a document with the inserted contents starting from a new page.

The detailed steps of merging documents by inserting the entire file are as follows:

  • Create an object of Document class and load a Word document from disk.
  • Insert another Word document entirely to the loaded document using Document.insertTextFromFile() method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;

public class merge {
    public static void main(String[] args) {
        //Create an object of Document and load a Word document from disk
        Document document = new Document("C:/Samples/Sample1.docx");

        //Insert another Word document entirely to the document
        document.insertTextFromFile("C:/Samples/Sample2.docx", FileFormat.Docx_2013);

        //Save the result document
        document.saveToFile("MergingResult.docx", FileFormat.Docx_2013);
    }
}

Java: Merge Word Documents

Merge Documents by Cloning Contents

If you want to merge documents without starting a new page, you can clone the contents of other documents to add to the end of a document.

The detailed steps of merging documents by cloning contents are as follows:

  • Create two objects of Document and load the two Word documents from disk.
  • Loop through the second document to get all the sections using Document.getSections() method, then loop through all the sections to get their child objects using Section.getBod().getChildObjects() method, then get the last section of the first document using Document.getLastSection() method, and then add the child objects to the last section of the first document using Body.getChildObjects().add() method.
  • Save the result document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;

public class mergeDocuments {
    public static void main(String[] args){
        //Create two Document objects and load two Word documents from disk
        Document document1 = new Document("C:/Samples/Sample1.docx");
        Document document2 = new Document("C:/Samples/Sample2.docx");

        //Loop through the second document to get all the sections
        for (Object sectionObj : (Iterable) document2.getSections()) {
            Section sec=(Section)sectionObj;
            //Loop through the sections of the second document to get their child objects
            for (Object docObj :(Iterable ) sec.getBody().getChildObjects()) {
                DocumentObject obj=(DocumentObject)docObj;

                //Get the last section of the first document
                Section lastSection = document1.getLastSection();

                //Add the child objects to the last section of the first document
                Body body = lastSection.getBody();
                body.getChildObjects().add(obj.deepClone());
            }
        }

        //Save the result document
        document1.saveToFile("MergingResult.docx", FileFormat.Docx_2013);
    }
}

Java: Merge Word Documents

Apply for a Temporary License

If you’d like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

I have a suggestion!
First the main method; the parameters are: test1=firstDocxFileName, test2=secondDocxFileName, dest=destinationFileName; document is a global variable;

    public void mergeDocx(String test1, String test2, String dest){


    try {
        XWPFDocument doc1 = new XWPFDocument(new FileInputStream(new File(test1)));
        XWPFDocument doc2 = new XWPFDocument(new FileInputStream(new File(test2)));
        document = new XWPFDocument();
        passaElementi(doc1);
        passaElementi(doc2);
        passaStili(doc1,doc2);
        OutputStream out = new FileOutputStream(new File(dest));
        document.write(out);
        out.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

The private method ‘passaElementi’copies and paste the body elements from doc1 to document object;I don’t know what is XWPFSDT object…; (pay attention: i don’t copy all the document but only the body!! .. for headers, sections, footers it proceed similarly) (the integer variables i and j are global and 0 at the beginning obviously)

private void passaElementi(XWPFDocument doc1){

    for(IBodyElement e : doc1.getBodyElements()){
        if(e instanceof XWPFParagraph){
            XWPFParagraph p = (XWPFParagraph) e;
            if(p.getCTP().getPPr()!=null && p.getCTP().getPPr().getSectPr()!=null){
                continue;
            }else{
                document.createParagraph();
                document.setParagraph(p, i);
                i++;
            }
        }else if(e instanceof XWPFTable){
            XWPFTable t = (XWPFTable)e;
            document.createTable();
            document.setTable(j, t);
            j++;
        }else if(e instanceof XWPFSDT){
            // boh!
        }

    }

}

The private method ‘passaStili’ copies and paste styles from doc1 and doc2 to document object;

private void passaStili(XWPFDocument doc1, XWPFDocument doc2){
    try {
        CTStyles c1 = doc1.getStyle();
        CTStyles c2 =  doc2.getStyle();
        int size1 = c1.getStyleList().size();
        int size2 = c2.getStyleList().size();
        for(int i = 0; i<size2; i++ ){
            c1.addNewStyle();
            c1.setStyleArray(size1+i, c2.getStyleList().get(i));
        }


        document.createStyles().setStyles(c1);
    } catch (XmlException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I don’t handle exceptions to be fast!
Leave a like if you liked it!
Best regards!

B.M.

Для нескольких файлов DOCX вы можете использовать POI для слияния для создания комбинации файлов DOCX. Этот метод будет передаваться вам. Тем не менее, есть картинки с изображениями в файле DOCX. Этот метод не обрабатывается. Друзья, которые нуждаются в нем, могут расширяться сами по себе.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
/**
 * Объединить два документа DOCX, что недействительно для картинки, содержащейся в документации
 * @author laitong.ma
   * @Date 17 сентября 2018 г.
 */
public class POIMergeDocUtil {
	public static void main(String[] args) throws Exception {
		
		String[] srcDocxs = {"e:\waxz_1.docx","e:\waxz_2.docx","e:\waxz_3.docx"};
		String destDocx = "e:\wzxz_new.docx";
		mergeDoc(srcDocxs, destDocx);
	}
	/**
	  * Merge Docx файл
	  * @param srcdocxs целевой файл docx должен быть объединен
	  * @param destdocx merge docx выходной файл
	 */
	public static void mergeDoc(String[] srcDocxs,String destDocx){
		
		OutputStream dest = null;
		List<OPCPackage> opcpList = new ArrayList<OPCPackage>();
		int length = null == srcDocxs ? 0 : srcDocxs.length;
		/**
		  * Циклы для получения объектов OpcPackage для каждого файла DOCX
		 */
		for (int i = 0; i < length; i++) {
			String doc = srcDocxs[i];
			OPCPackage srcPackage =  null;
			try {
				srcPackage = OPCPackage.open(doc);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(null != srcPackage){
				opcpList.add(srcPackage);
			}
		}
		
		int opcpSize = opcpList.size();
		 // Когда полученный объект OpcPackage больше 0, выполните операцию слияния
		if(opcpSize > 0){
			try {
				dest = new FileOutputStream(destDocx);
				XWPFDocument src1Document = new XWPFDocument(opcpList.get(0));
				CTBody src1Body = src1Document.getDocument().getBody();
				 // opcpackage часть части операции слияния более 1
				if(opcpSize > 1){
					for (int i = 1; i < opcpSize; i++) {
						OPCPackage src2Package = opcpList.get(i);
						XWPFDocument src2Document = new XWPFDocument(src2Package);
						CTBody src2Body = src2Document.getDocument().getBody();
						appendBody(src1Body, src2Body);
					}
				}
				 // записать объединенный документ в целевой файл
				src1Document.write(dest);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
                                 // Обратите внимание на следующие части, чтобы удалить влиятельный целевой файл srcDocxs.
				/*for (OPCPackage opcPackage : opcpList) {
					if(null != opcPackage){
						try {
							opcPackage.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}*/
				 // закрытие течет
				IOUtils.closeQuietly(dest);
			}
		}
		
		
	}
	
	/**
	  * Объединение содержимого документа
	  * @param SRC Целевой документ
	  * @param добавить документ для объединения
	 * @throws Exception
	 */
	private static void appendBody(CTBody src, CTBody append) 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("<"));
		CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart
				+ sufix);
		src.set(makeBody);
	}

First text file
A.txt;

asdfghjklqw12345 qwe3456789
asdfghjklqw12345 qwe3456789

Second text file
B.txt;

|Record 1: Rejected — Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|
|Record 2: Rejected — Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

Third text file
C.txt;

asdfghjklqw12345 qwe3456789 |Record 1: Rejected — Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

asdfghjklqw12345 qwe3456789 |Record 2: Rejected — Error on table AUTHORIZATION_TBL, column AUTH_DATE.ORA-01843: not a valid month|

for the above situation where I want to merge two lines from two different text files into one line.My code is below

    List<FileInputStream> inputs = new ArrayList<FileInputStream>();
    File file1 = new File("C:/Users/dell/Desktop/Test/input1.txt");
    File file2 = new File("C:/Users/dell/Desktop/Test/Test.txt");

    FileInputStream fis1;
    FileInputStream fis2;

    try {
        fis1 = new FileInputStream(file1);
        fis2= new FileInputStream(file2);

        inputs.add(fis1);
        inputs.add(fis2);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    int total = (int) (file1.length() + file2.length());
    System.out.println("total length is " + total);

    SequenceInputStream sis = new                                                            SequenceInputStream(Collections.enumeration(inputs));
    try {
        System.out.println("SequenceInputStream.available() = "+ sis.available());

        byte[] merge = new byte[total];

        int soFar = 0;
        do {
            soFar += sis.read(merge,total - soFar, soFar);
        } while (soFar != total);
        DataOutputStream dos = new DataOutputStream(new        FileOutputStream("C:/Users/dell/Desktop/Test/C.txt"));
        soFar = 0;
        dos.write(merge, 0, merge.length);
        dos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Понравилась статья? Поделить с друзьями:
  • Java word to text
  • Javascript reading excel file
  • Java word to number one
  • Java word for number
  • Javascript if word is in string