我讀了一個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」 –