我正在制作一个应获取docx文件的程序,并将用户添加的内容添加到某些文本字段中。但是模板已经有水印和预设的标头。
我试图使用Apache POI进行创建,但是当我创建新文件时,所有模板都丢失了。它仅保存文本。然后,我了解了“ docx4j”,但是页面不可用,找不到其他软件可以下载该库。
public static void main(String[] args) throws Exception {
int count = 0;
XWPFDocument document = new XWPFDocument();
XWPFDocument docx = new XWPFDocument(new FileInputStream("Plantilla.docx"));
XWPFWordExtractor we = new XWPFWordExtractor(docx);
String text = we.getText() ;
if(text.contains("Cambio")){
text = text.replace("Cambio", "cambio");
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();
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("test3.docx"));
}
}