我有這段代碼。我希望它能幫助你解決你的問題。有了它,你可以從.docx中讀取你要改變的單詞。更改此詞並將新段落保存在新文檔中。
//WriteDocx.java
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class WriteDocx
{
public static void main(String[] args) throws Exception {
int count = 0;
XWPFDocument document = new XWPFDocument();
XWPFDocument docx = new XWPFDocument(new FileInputStream("Bonjour1.docx"));
XWPFWordExtractor we = new XWPFWordExtractor(docx);
String text = we.getText() ;
if(text.contains("SMS")){
text = text.replace("SMS", "sms");
System.out.println(text);
}
char[] c = text.toCharArray();
for(int i= 0; i < c.length;i++){
if(c[i] == '\n'){
count ++;
}
}
System.out.println(c[0]);
StringTokenizer st = new StringTokenizer(text,"\n");
XWPFParagraph para = document.createParagraph();
para.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = para.createRun();
run.setBold(true);
run.setFontSize(36);
run.setText("Apache POI works well!");
List<XWPFParagraph>paragraphs = new ArrayList<XWPFParagraph>();
List<XWPFRun>runs = new ArrayList<XWPFRun>();
int k = 0;
for(k=0;k<count+1;k++){
paragraphs.add(document.createParagraph());
}
k=0;
while(st.hasMoreElements()){
paragraphs.get(k).setAlignment(ParagraphAlignment.LEFT);
paragraphs.get(k).setSpacingAfter(0);
paragraphs.get(k).setSpacingBefore(0);
run = paragraphs.get(k).createRun();
run.setText(st.nextElement().toString());
k++;
}
document.write(new FileOutputStream("test2.docx"));
}
}
PS:XWPFDocument DOCX =新XWPFDocument(新的FileInputStream( 「Bonjour1.docx」))
必須與文件名從那裏您將要替換某些字變 「Bonjour1.docx」 或短語。 我用APACHE POI library 我需要一些代碼從這個網站HANDLING MS WORD DOCUMENTS USING APACHE POI
UPDATE
你試過apache-poi嗎? – Jayan 2014-10-19 16:18:21