我想要編輯.doc(word)文檔的標題。下面的代碼,我已經寫了:使用java在.doc中添加圖像和編輯標題
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();
}
}
}
但其沒有工作,下面的代碼執行後,它是不能夠打開新的文件顯示錯誤。我還需要在文檔中提供的框中添加圖片。任何機構有任何想法如何做到這一點?
下面是鏈接我也嘗試:讓同樣的錯誤
Replacing variables in a word document template with java
:
您使用的是哪個版本的Apache POI?如果不是最新的,你可以試試最新的? – centic
Apache POI 3.13 –