Abra o Microsoft Word em Java
-
21-08-2019 - |
Pergunta
Eu estou tentando abrir o documento MS Word 2003 em java, procurar uma cadeia especificada e substituí-la por uma nova cadeia. Eu uso Apache POI para fazer isso. Meu código é como o seguinte:
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);
}
}
Eu chamo esta função com as seguintes argumentos:
HashMap<String, String> replacements = new HashMap<String, String>();
replacements.put("AAA", "BBB");
searchAndReplace("C:/Test.doc", "C:/Test1.doc", replacements);
Quando o arquivo Test.doc contém uma linha simples como este: " AAA EEE ", que funciona com êxito, mas quando eu uso um arquivo complicado ele irá ler o conteúdo com sucesso e gerar o Test1. arquivo doc mas quando eu tentar abri-lo, ele vai me dar o seguinte erro:
Word não conseguiu ler este documento. Ele pode estar corrompido. Tente um ou mais dos seguintes: * Abrir e reparar o arquivo. * Abra o arquivo com texto conversor de recuperação. (C: \ Test1.doc)
Por favor me diga o que fazer, porque eu sou um novato no POI e eu não ter encontrado um bom tutorial para ele.
Solução
Você poderia tentar OpenOffice API , mas há arent muitos recursos lá fora, para dizer-lhe como usá-lo.
Outras dicas
Em primeiro lugar você deve estar fechando seu documento.
Além disso, o que eu sugiro fazer é resaving seu documento original do Word como um documento XML do Word, em seguida, alterando a extensão manualmente a partir .XML para .doc. Então olha para o XML do documento real que você está trabalhando com e rastrear o conteúdo para se certificar de que você não está editando acidentalmente valores hexadecimais (AAA e EEE poderia ser valores hexadecimais em outros campos).
Sem ver o documento do Word real é difícil dizer o que está acontecendo.
Não existe muita documentação sobre POI em tudo, especialmente para documento do Word, infelizmente.
Eu não sei:. É o seu OK para me responder, mas apenas para compartilhar o conhecimento, eu vou me responder
Depois de navegar na web, a solução final que eu encontrei é: A Biblioteca chamado docx4j é muito bom para lidar com MS docx arquivo , embora sua documentação não é suficiente até agora e seu fórum ainda está em etapas iniciais, mas no geral me ajudar a fazer o que eu preciso ..
Graças 4 todos os que me ajudar ..
Você também pode tentar este: http://www.dancrintea.ro/doc -a-pdf /
Looks como este poderia ser o problema.