Last active
August 19, 2019 10:12
-
-
Save riversun/4ea1d2941587f4abcd42318123bba2c0 to your computer and use it in GitHub Desktop.
[SOF][Apache POI]Read docx file as XWPFDocument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
中国人民
哈哈哈