Skip to content

Instantly share code, notes, and snippets.

@riversun
Last active August 19, 2019 10:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riversun/4ea1d2941587f4abcd42318123bba2c0 to your computer and use it in GitHub Desktop.
Save riversun/4ea1d2941587f4abcd42318123bba2c0 to your computer and use it in GitHub Desktop.
[SOF][Apache POI]Read docx file as XWPFDocument
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class ReadAndEditWord {
public static void main(String[] args) throws Exception {
Path path = Paths.get("c:/temp/example.docx");
byte[] byteData = Files.readAllBytes(path);
// read as XWPFDocument from byte[]
XWPFDocument doc = new XWPFDocument(new ByteArrayInputStream(byteData));
int numberToPrint = 0;
// you can edit paragraphs
for (XWPFParagraph para : doc.getParagraphs()) {
List<XWPFRun> runs = para.getRuns();
numberToPrint++;
for (XWPFRun run : runs) {
// read text
String text = run.getText(0);
// edit text and update it
run.setText(numberToPrint + " " + text, 0);
}
}
// save it
FileOutputStream fos = new FileOutputStream(new File("c:/temp/example2.docx"));
doc.write(fos);
}
}
if you wanna use org.apache.poi.xwpf.* like org.apache.poi.xwpf.usermodel.XWPFDocument you should also add 'poi-ooxml' as well.
POM.xml(partial)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
@tinyzhi
Copy link

tinyzhi commented Apr 23, 2019

中国人民
哈哈哈

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment