.doc (워드) 문서의 헤더를 편집하고 싶습니다. 코드 아래 내가 쓴 :자바를 사용하여 .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 –