java 使用JAVA写入word文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39762373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:36:53  来源:igfitidea点击:

Write into a word file using JAVA

javaapache-poi

提问by Mehul Jain

I read a word document and want to write into another word file using Java. I want the style (font, bold, italic, heading, etc.) of the content in the read document to be written as it is the new document created. I am able to copy the content but not the format style.

我读了一个 word 文档,想用 Java 写入另一个 word 文件。我希望阅读文档中内容的样式(字体、粗体、斜体、标题等)被写入,因为它是创建的新文档。我可以复制内容,但不能复制格式样式。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.util.List;

public class ReadFile 
{
    public static void main(String[] args)throws Exception 
    {

        XWPFDocument docx = new XWPFDocument(new  FileInputStream("d:\Profiles\mehjain\Desktop\Test1.docx"));
        List<XWPFParagraph> paragraphList =  docx.getParagraphs();

        XWPFDocument document= new XWPFDocument(); 
        FileOutputStream out = new FileOutputStream(new File("d:\Profiles\mehjain\Desktop\Test2.docx"));
        XWPFParagraph n = document.createParagraph();
        XWPFRun run=n.createRun();

        for (XWPFParagraph paragraph: paragraphList)
        { 
            run.setText(paragraph.getText());              
            run.addCarriageReturn();
        }
        document.write(out); 
        document.close();   
        out.close();
        System.out.println("Test2.docx written successfully");
    }
}

I got an answer to copy the same format of text but I am unable to copy numbers. I executed this code:

我得到了复制相同格式文本的答案,但我无法复制数字。我执行了这段代码:

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.IBody;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFStyle;
import org.apache.poi.xwpf.usermodel.XWPFStyles;
import java.util.List;

public class ReadFile 
{
public static void main(String[] args)throws Exception 
{

  XWPFDocument docx = new XWPFDocument(new    FileInputStream("d:\Profiles\mehjain\Desktop\Test1.docx"));

  List<XWPFParagraph> paragraphList =  docx.getParagraphs();

   XWPFDocument document= new XWPFDocument(); 
   FileOutputStream out = new FileOutputStream(new File("d:\Profiles\mehjain\Desktop\Test2.docx"));
   XWPFParagraph n = document.createParagraph();



  for (XWPFParagraph paragraph : paragraphList)
  {

       for(XWPFRun run1 : paragraph.getRuns())
       {
         XWPFRun run=n.createRun();
         run.setText(run1.getText(0));
        run.setFontFamily( run1.getFontFamily() );
        run.setBold( run1.isBold() );
        run.setItalic( run1.isItalic() );
        run.setStrike( run1.isStrike() );
        run.setColor( run1.getColor() );
        }
       XWPFRun run=n.createRun();
       run.addCarriageReturn();
    }
   document.write(out); 
   document.close();   
   out.close();
   System.out.println("Test2.docx written successfully"); 
  }
  }

回答by PlsWork

This might help:

这可能有帮助:

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class FontStyle 
{
   public static void main(String[] args)throws Exception 
   {
   //Blank Document
   XWPFDocument document= new XWPFDocument(); 

   //Write the Document in file system
   FileOutputStream out = new FileOutputStream(
   new File("fontstyle.docx"));

   //create paragraph
   XWPFParagraph paragraph = document.createParagraph();

   //Set Bold an Italic
   XWPFRun paragraphOneRunOne = paragraph.createRun();
   paragraphOneRunOne.setBold(true);
   paragraphOneRunOne.setItalic(true);
   paragraphOneRunOne.setText("Font Style");
   paragraphOneRunOne.addBreak();

   //Set text Position
   XWPFRun paragraphOneRunTwo = paragraph.createRun();
   paragraphOneRunTwo.setText("Font Style two");
   paragraphOneRunTwo.setTextPosition(100);

   //Set Strike through and Font Size and Subscript
   XWPFRun paragraphOneRunThree = paragraph.createRun();
   paragraphOneRunThree.setStrike(true);
   paragraphOneRunThree.setFontSize(20);
   paragraphOneRunThree.setSubscript(
   VerticalAlign.SUBSCRIPT);
   paragraphOneRunThree.setText(" Different Font Styles");

   document.write(out);
   out.close();
   System.out.println("fontstyle.docx written successully");
   }
}

Props to: http://www.tutorialspoint.com/apache_poi_word/apache_poi_word_font_style.htm

道具:http: //www.tutorialspoint.com/apache_poi_word/apache_poi_word_font_style.htm

回答by Axel Richter

Copying whole paragraphs from one Worddocx to another will be simpler than taking all the content from one Worddocx to a single run in a single paragraph of another. And since you stated that there are numberings in the source docx, the whole paragraphs are needed since only paragraphs can be numbered.

将一个Worddocx 中的整个段落复制到另一个 docx 比将一个Worddocx 中的所有内容复制到另一个文档的单个段落中更简单。并且由于您指出源 docx 中有编号,因此需要整个段落,因为只能对段落进行编号。

But to copy the numberings, the /word/numbering.xmlmust also be copied. So if the Test1.docx looks like this: enter image description here

但是要复制编号,/word/numbering.xml也必须复制。所以如果 Test1.docx 看起来像这样: 在此处输入图片说明

After processing the following program:

处理完以下程序后:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTNumbering;

import java.util.List;
import java.lang.reflect.Field;

public class CopyWordParagraphsDocToDoc {
 public static void main(String[] args)throws Exception {

  XWPFDocument docx1 = new XWPFDocument(new  FileInputStream("Test1.docx"));
  XWPFNumbering numberingDocx1 = docx1.getNumbering();
  // get paragraphListDocx1 as a List of all paragraphs from docx1
  List<XWPFParagraph> paragraphListDocx1 =  docx1.getParagraphs();

  // get the numbering.xml from docx1 to docx2
  // this is needed if some of the paragraphs from docx1 are numbered
  XWPFDocument docx2= new XWPFDocument(); 
  if (numberingDocx1 != null) {
   XWPFNumbering numberingDocx2 = docx2.createNumbering();
   try {
    Field f = numberingDocx1.getClass().getDeclaredField("ctNumbering");
    f.setAccessible(true);
    numberingDocx2.setNumbering((CTNumbering)f.get(numberingDocx1));
   } catch (NoSuchFieldException nsfex) {
   } catch (IllegalAccessException iaex) {
   }
  }

  // create a paragraph in docx2
  XWPFParagraph paragraphDocx2 = docx2.createParagraph();
  XWPFRun run = paragraphDocx2.createRun();
  run.setText("This is from Test1.docx:");

  // this will copy all paragraphs from paragraphListDocx1 to docx2
  for (XWPFParagraph paragraphDocx1 : paragraphListDocx1) { 
   paragraphDocx2 = docx2.createParagraph();
   docx2.setParagraph(paragraphDocx1, docx2.getPosOfParagraph(paragraphDocx2));            
  }

  paragraphDocx2 = docx2.createParagraph();
  run = paragraphDocx2.createRun();
  run.setText("^-- this was from Test1.docx.");


  FileOutputStream out = new FileOutputStream(new File("Test2.docx"));
  docx2.write(out); 
  docx2.close();   

  System.out.println("Test2.docx written successfully");
 }
}

The Test2.docx will look like this:

Test2.docx 将如下所示:

enter image description here

在此处输入图片说明

Note: Tables will not be copied since we only copy paragraphs. Pictures will be broken since the /word/media/*.*is not copied. Special stylings like "Heading 1" will not be copied since we not copy /word/styles.xml.

注意:表格不会被复制,因为我们只复制段落。由于/word/media/*.*未复制,图片将被损坏。因为我们不复制,所以不会复制像“标题 1”这样的特殊样式/word/styles.xml

回答by optimistic_creeper

You can use Files copy method from java. Use the below code snippet:

您可以使用 java 中的文件复制方法。使用以下代码片段:

Files.copy(new File("source path location"), new File("destination path location"));

Hope that, it serves the purpose.

希望,它达到了目的。