내 프로젝트에서이 예제를 사용하고 있습니다. 모든 것이 잘되고 텍스트를 대체하는 것도 좋습니다. 그러나 "센터링"해야하는 출력 텍스트 파일에서는 왼쪽 정렬이됩니다. 입력 파일 - .doc, 나는 문서 형식을 깨뜨리고 있다고 느끼지만 문제가 무엇인지 잘 모르겠습니다. 이 문제를 해결하는 방법?Apache-POI 형식의 .doc 파일 형식의 텍스트 문제
public class HWPFTest {
public static void main(String[] args){
String filePath = "F:\\Sample.doc";
POIFSFileSystem fs = null;
try {
fs = new POIFSFileSystem(new FileInputStream(filePath));
HWPFDocument doc = new HWPFDocument(fs);
doc = replaceText(doc, "$VAR", "MyValue1");
saveWord(filePath, doc);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
private static HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText){
Range r1 = doc.getRange();
for (int i = 0; i < r1.numSections(); ++i) {
Section s = r1.getSection(i);
for (int x = 0; x < s.numParagraphs(); x++) {
Paragraph p = s.getParagraph(x);
for (int z = 0; z < p.numCharacterRuns(); z++) {
CharacterRun run = p.getCharacterRun(z);
String text = run.text();
if(text.contains(findText)) {
run.replaceText(findText, replaceText);
}
}
}
}
return doc;
}
private static void saveWord(String filePath, HWPFDocument doc) throws FileNotFoundException, IOException{
FileOutputStream out = null;
try{
out = new FileOutputStream(filePath);
doc.write(out);
}
finally{
out.close();
}
}
}
docx 파일을 사용할 수 있다고 생각합니다. 압축을 풀고 내용을 바꾸고 지퍼 백. 나는 개인적으로 ods/odt 파일을 위해 그것을한다. – user1516873
@ user1516873 POI 프로젝트가 docx에서 견인을 받기 전에 POI 프로젝트를 사용하여 사용자 지정 docx 관련 파트를 개발했습니다. DOCX 형식의 미묘한 부분이 있습니다. 간단한 형식으로 내용을 바꾸면 내용이 손상됩니다. 물론 여러 시나리오에서 작동하지만, 실제로 작동해야하는 경우 심각한 추가 노력에 직면합니다. –
@RainerSchwarze이 점에 대해 메모 해 드리겠습니다. 감사합니다. OpenOffice 형식의 경우에는 그런 문제가 없습니다. – user1516873