Dear all
There are problem when I want to replace text-elements with apache poi. But
not finding the replacing-method is the problem - the doc is damaged and
unable to be opened after writing.
The line which causes the error is the following:
"p.replaceText(searchText, replaceTxt, offset);"
error-message
-------------
“Word was unable to read this document. It may be corrupt.
Try one or more of the following:
* Open and Repair the file.
* Open the file with the Text Recovery converter.
(\…\test.doc)”
Can you help me - is there a workaround?
Thx Thomas
my code:
String file_in_path =
"C:/Users/Thomas/Desktop/20110729/BN_Vertragsdaten_123.doc";
String file_out_path =
"C:/Users/Thomas/Desktop/20110729/ausgabe_BN_Vertragsdaten_123.doc";
String searchText = "Vertragsart";
String replaceTxt = "NEW_Vertragsart_NEW";
HWPFDocument doc = null;
try {
POIFSFileSystem ps = new POIFSFileSystem(new
FileInputStream(file_in_path));
doc = new HWPFDocument(ps);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Range range = doc.getRange();
for (int x = 0; x < range.numSections(); x++) {
Section s = range.getSection(x);
for (int y = 0; y < s.numParagraphs(); y++) {
Paragraph p = s.getParagraph(y);
String paraText = p.text();
int offset = paraText.indexOf(searchText);
if (offset != -1) {
System.out.println("REPLACED");
p.replaceText(searchText, replaceTxt, offset);
}
}
}
try {
OutputStream out = new FileOutputStream(file_out_path);
doc.write(out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
--
View this message in context: http://apache-poi.1045710.n5.nabble.com/open-doc-replaceText-save-doc-ERROR-Word-was-unable-to-read-this-document-It-may-be-corrupt-tp4649703p4649703.html
Sent from the POI - User mailing list archive at Nabble.com.
---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@poi.apache.org
For additional commands, e-mail: user-help@poi.apache.org
|