我读了一个word文档并想用Java写入另一个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");
}
}
我得到了一个答案,复制相同格式的文本,但我无法复制数字。 我执行这个代码:
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");
}
}
将整个段落从Test1.docx复制到Test2.docx是一个选项吗?这可以使用'XWPFDocument'的方法'setParagraph(XWPFParagraph paragraph,int pos)'。 –
你是什么意思,“我无法复制数字”?你的意思是编号清单(段落)?再说一遍:将Test1.docx中的整个段落复制到Test2.docx是否是一个选项?或者将Test1.docx中的多个段落的内容放入Test2.docx中的一个段落中? –
假设 “1.简介”存在于Test1.Docx中。 所以,我只能复制Test2.docx中的“Introduction” –