0

.doc(word)文書のヘッダーを編集したい。私が書いたコードの下に:

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Section;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

public class WordReplaceText {
    public static final String SOURCE_FILE = "C:\\Users\\609650323\\Desktop\\Files\\Project\\GFAST\\surveyPack.doc";
    public static final String OUTPUT_FILE = "C:\\Users\\609650323\\Desktop\\Files\\Project\\GFAST\\surveyPack2.doc";

    public static void main(String[] args) throws Exception {
        WordReplaceText instance = new WordReplaceText();
        HWPFDocument doc = instance.openDocument(SOURCE_FILE);
        if (doc != null) {
            doc = instance.replaceText(doc,  "${A}", "AField");
            instance.saveDocument(doc, OUTPUT_FILE);

        }

    }

    private HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText) {
        Range r = doc.getRange();
        for (int i = 0; i < r.numSections(); ++i) {
            Section s = r.getSection(i);
            for (int j = 0; j < s.numParagraphs(); j++) {
                Paragraph p = s.getParagraph(j);
                for (int k = 0; k < p.numCharacterRuns(); k++) {
                    CharacterRun run = p.getCharacterRun(k);
                    String text = run.text();
                    if (text.contains(findText)) {
                        run.replaceText(findText, replaceText);
                    }
                }
            }
        }
        return doc;
    }

    private HWPFDocument openDocument(String file) throws Exception {
        URL res = getClass().getClassLoader().getResource(file);
        HWPFDocument document = null;
        if (res != null) {
            document = new HWPFDocument(new POIFSFileSystem(new File(res.getPath())));
        }else
            document = new HWPFDocument(new POIFSFileSystem(new File(SOURCE_FILE)));
        return document;
    }

    private void saveDocument(HWPFDocument doc, String file) {
        try {
            FileOutputStream out = new FileOutputStream(file);
            doc.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

しかし、以下のコードを実行した後、エラーを表示して新しいドキュメントを開くことができません。また、ドキュメントで提供されているボックスに写真を追加する必要があります。それを行う方法を知っている体はありますか?

以下は私も試したリンクです:

Word 文書テンプレートの変数を Java に置き換える

同じエラーが発生します:

ここに画像の説明を入力

4

1 に答える 1