java에서 MS Word 2003 문서를 열고 지정된 String을 검색 한 다음 새 String으로 바꾸려고합니다. APACHE POI를 사용합니다. 내 코드는 다음처럼입니다 :Java에서 Microsoft Word 열기
나는 다음 인수로이 함수를 호출public void searchAndReplace(String inputFilename, String outputFilename,
HashMap<String, String> replacements) {
File outputFile = null;
File inputFile = null;
FileInputStream fileIStream = null;
FileOutputStream fileOStream = null;
BufferedInputStream bufIStream = null;
BufferedOutputStream bufOStream = null;
POIFSFileSystem fileSystem = null;
HWPFDocument document = null;
Range docRange = null;
Paragraph paragraph = null;
CharacterRun charRun = null;
Set<String> keySet = null;
Iterator<String> keySetIterator = null;
int numParagraphs = 0;
int numCharRuns = 0;
String text = null;
String key = null;
String value = null;
try {
// Create an instance of the POIFSFileSystem class and
// attach it to the Word document using an InputStream.
inputFile = new File(inputFilename);
fileIStream = new FileInputStream(inputFile);
bufIStream = new BufferedInputStream(fileIStream);
fileSystem = new POIFSFileSystem(bufIStream);
document = new HWPFDocument(fileSystem);
docRange = document.getRange();
numParagraphs = docRange.numParagraphs();
keySet = replacements.keySet();
for (int i = 0; i < numParagraphs; i++) {
paragraph = docRange.getParagraph(i);
text = paragraph.text();
numCharRuns = paragraph.numCharacterRuns();
for (int j = 0; j < numCharRuns; j++) {
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
System.out.println("Character Run text: " + text);
keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
key = keySetIterator.next();
if (text.contains(key)) {
value = replacements.get(key);
charRun.replaceText(key, value);
docRange = document.getRange();
paragraph = docRange.getParagraph(i);
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
}
}
}
}
bufIStream.close();
bufIStream = null;
outputFile = new File(outputFilename);
fileOStream = new FileOutputStream(outputFile);
bufOStream = new BufferedOutputStream(fileOStream);
document.write(bufOStream);
} catch (Exception ex) {
System.out.println("Caught an: " + ex.getClass().getName());
System.out.println("Message: " + ex.getMessage());
System.out.println("Stacktrace follows.............");
ex.printStackTrace(System.out);
}
}
:
HashMap<String, String> replacements = new HashMap<String, String>();
replacements.put("AAA", "BBB");
searchAndReplace("C:/Test.doc", "C:/Test1.doc", replacements);
Test.doc를 파일이 같은 간단한 라인을 포함 : "AAA의 EEE을" 그것은 성공적으로 작동하지만 복잡한 파일을 사용할 때 내용을 성공적으로 읽고 Test1.doc 파일을 생성하지만 열려고하면 다음과 같은 오류가 발생합니다.
Word not t o이 문서를 읽으십시오. 손상되었을 수 있습니다. 다음 중 하나 이상을 시도하십시오. * 파일을 열어 복구하십시오. * 텍스트 복구 변환기로 파일을 엽니 다. (C : \ Test1.doc)
내가 POI의 초보자이기 때문에해야 할 일을 알려주십시오. 좋은 지침서를 찾지 못했습니다.
대단히 감사합니다. 이러한 API를 .docx 파일을 열 때만 사용하고 XML 파일로 핵심 문서를 가져 와서 XML 파서를 사용하여 구문 분석 한 다음 XPath를 사용하여 필요한 항목을 검색하면 모든 것이 정상입니다. 또 다른 솔루션, OpenXML API가 없으면 MSWord 2007에서 .docx 파일을 열고 XML 파일 -NOT 2003 XML-로 저장하고 XML 파일을 Java로 구문 분석 한 다음 필요한 것을 바꿀 수 있습니다. 이 솔루션에서는 이미지를 대체 할 수도 있습니다. XML 파일에 Base64로 인코딩 된 문자열로 저장된 이미지이며이 문자열을 Base64 인코딩을 사용하는 다른 이미지의 인코딩을 나타내는 다른 문자열로 바꿀 수 있습니다 – Saeed