我正在使用POI读取.doc文件,我希望选择一些内容来形成新的.doc文件。具体来说,是否可以将“范围”中的“段落”内容写入新文件?谢谢。
HWPFDocument doc = new HWPFDocument(fs);
Range range = doc.getRange();
for (int i = 0; i < range.numParagraphs(); i++) {
//here I wish to write the content in a Paragraph
//into a new .doc file "doc1""doc2"
//instead of doc.write(pathName) that only write one .doc file.
}发布于 2014-08-04 09:51:32
下面是处理当前任务的代码。在这里,选择段落的标准非常简单:第11..20段转到文件"us.docx",第21..30 -到"japan.docx“。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class SplitDocs {
public static void main(String[] args) {
FileInputStream in = null;
HWPFDocument doc = null;
XWPFDocument us = null;
XWPFDocument japan = null;
FileOutputStream outUs = null;
FileOutputStream outJapan = null;
try {
in = new FileInputStream("wto.doc");
doc = new HWPFDocument(in);
us = new XWPFDocument();
japan = new XWPFDocument();
Range range = doc.getRange();
for (int parIndex = 0; parIndex < range.numParagraphs(); parIndex++) {
Paragraph paragraph = range.getParagraph(parIndex);
String text = paragraph.text();
System.out.println("***Paragraph" + parIndex + ": " + text);
if ( (parIndex >= 11) && (parIndex <= 20) ) {
createParagraphInAnotherDocument(us, text);
} else if ( (parIndex >= 21) && (parIndex <= 30) ) {
createParagraphInAnotherDocument(japan, text);
}
}
outUs = new FileOutputStream("us.docx");
outJapan = new FileOutputStream("japan.docx");
us.write(outUs);
japan.write(outJapan);
in.close();
outUs.close();
outJapan.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void createParagraphInAnotherDocument(XWPFDocument document, String text) { XWPFParagraph newPar = document.createParagraph();
newPar.createRun().setText(text, 0);
}
}我使用.docx作为输出,因为向.docx添加新段落比添加到.doc文件要容易。现在不再推荐将新的insertAfter(ParagraphProperties props, int styleIndex)插入到给定的range中的方法(我使用POIVersion3.10),并且我无法找到在空的.doc文件中创建一个新的段落对象的简单而合理的方法。然而,使用直截了当和干净的XWPFParagraph newPar = document.createParagraph();是一种乐趣。
但是,根据任务中的要求,此代码使用.doc作为输入。希望这会有所帮助:)
在这里,我们使用一个简单的选择标准,使用段落索引。如果您需要类似字体的条件,正如您所说的,您可能会发布另一个问题,或者您可能会自己找到解决方案。不管怎么说,有了docx,事情就容易多了。
发布于 2016-07-13 21:17:07
这是相同的情况,我有过,请检查Apache POI - Split Word document (docx) to pages的解决方案。值得注意的是,虽然这个解决方案比上面提供的解决方案更好,因为它生成了格式化的页面,但是它在处理表和图像方面还不够。
https://stackoverflow.com/questions/25092384
复制相似问题