如何使用JAVA POI将.doc拆分为几个.doc?

飞鼠

我正在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.
}
丹尼斯·弗拉什

因此,这是当前任务适用的代码。这里选择段落的标准非常简单:段落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)将新对象插入Paragraph给定对象的方法range(我使用POI版本3.10),而且我找不到在空的.doc文件中创建新的Paragraph对象的简便且合乎逻辑的方法。而使用简单明了很高兴XWPFParagraph newPar = document.createParagraph();

但是,此代码根据您的任务要求将.doc用作输入。希望这会有所帮助:)

PS在这里,我们使用一个简单的选择标准,即段落索引。如您所说,如果您需要诸如字体标准之类的内容,则可能会提出其他问题,或者您可能会自己找到解决方案。无论如何,有了docx,事情变得更容易了。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章