Cập nhật thông tin chi tiết về Parse Word Document Using Apache Poi Example mới nhất trên website Trucbachconcert.com. Hy vọng nội dung bài viết sẽ đáp ứng được nhu cầu của bạn, chúng tôi sẽ thường xuyên cập nhật mới nội dung để bạn nhận được thông tin nhanh chóng và chính xác nhất.
In this article we will be discussing about ways and techniques to read word documents in Java using Apache POI library. The word document may contain images, tables or plain text. Apart from this a standard word file has header and footers too. Here in the following examples we will be parsing a word document by reading its different paragraph, runs, images, tables along with headers and footers. We will also take a look into identifying different styles associated with the paragraphs such as font-size, font-family, font-color etc.
Maven Dependencies
Following is the poi maven depedency required to read word documents. For latest artifacts visit here
chúng tôi
<dependencies> <dependency> <groupId>org.apache.poi
</groupId> <artifactId>poi-ooxml
</artifactId> <version>3.16
</version> </dependency> </dependencies>Reading Complete Text from Word Document
The class XWPFDocument has many methods defined to read and extract .docx file contents. getText() can be used to read all the texts in a .docx word document. Following is an example.
TextReader.java
public class
TextReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); XWPFWordExtractor extractor =new
XWPFWordExtractor(xdoc); System.out
.println(extractor.getText()); }catch
(Exception ex) { ex.printStackTrace(); } } }Reading Headers and Foooters of Word Document
HeaderFooter.java
public class
HeaderFooterReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); XWPFHeaderFooterPolicy policy =new
XWPFHeaderFooterPolicy(xdoc); XWPFHeader header = policy.getDefaultHeader();if
(header !=null
) { System.out
.println(header.getText()); } XWPFFooter footer = policy.getDefaultFooter();if
(footer !=null
) { System.out
.println(footer.getText()); } }catch
(Exception ex) { ex.printStackTrace(); } } }Output
This is Header
This is footer
Read Each Paragraph of a Word Document
Among the many methods defined in XWPFDocument class, we can use getParagraphs() to read a .docx word document paragraph chúng tôi method returns a list of all the paragraphs(XWPFParagraph) of a word document. Again the XWPFParagraph has many utils method defined to extract information related to any paragraph such as text alignment, style associated with the paragrpahs.
To have more control over the text reading of a word document,each paragraph is again divided into multiple runs. Run defines a region of text with a common set of properties.Following is an example to read paragraphs from a .docx word document.
ParagraphReader.java
public class
ParagraphReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); List paragraphList = xdoc.getParagraphs();for
(XWPFParagraph paragraph : paragraphList) { System.out
.println(paragraph.getText()); System.out
.println(paragraph.getAlignment()); System.out
.print(paragraph.getRuns().size()); System.out
.println(paragraph.getStyle());// Returns numbering format for this paragraph, eg bullet or lowerLetter.
System.out
.println(paragraph.getNumFmt()); System.out
.println(paragraph.getAlignment()); System.out
.println(paragraph.isWordWrapped()); System.out
.println("********************************************************************"
); } }catch
(Exception ex) { ex.printStackTrace(); } } }Reading Tables from Word Document
Following is an example to read tables present in a word document. It will print all the text rows wise.
TableReader.java
public class
TableReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); Iterator bodyElementIterator = xdoc.getBodyElementsIterator();while
(bodyElementIterator.hasNext()) { IBodyElement element = bodyElementIterator.next();if
("TABLE"
.equalsIgnoreCase(element.getElementType().name())) { List tableList = element.getBody().getTables();for
(XWPFTable table : tableList) { System.out
.println("Total Number of Rows of Table:"
+ table.getNumberOfRows());for
(int
i = 0; i for (int
j = 0; j out.println(table.getRow(i).getCell(j).getText()); } } } } } }catch
(Exception ex) { ex.printStackTrace(); } } }Reading Styles from Word Document
Styles are associated with runs of a paragraph. There are many methods available in the XWPFRun class to identify the styles associated with the text.There are methods to identify boldness, highlighted words, capitalized words etc.
StyleReader.java
public class
StyleReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); List paragraphList = xdoc.getParagraphs();for
(XWPFParagraph paragraph : paragraphList) {for
(XWPFRun rn : paragraph.getRuns()) { System.out
.println(rn.isBold()); System.out
.println(rn.isHighlighted()); System.out
.println(rn.isCapitalized()); System.out
.println(rn.getFontSize()); } System.out
.println("********************************************************************"
); } }catch
(Exception ex) { ex.printStackTrace(); } } }Reading Image from Word Document
Following is an example to read image files from a word document.
public class
ImageReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); List pic = xdoc.getAllPictures();if
(!pic.isEmpty()) { System.out
.print(pic.get(0).getPictureType()); System.out
.print(pic.get(0).getData()); } }catch
(Exception ex) { ex.printStackTrace(); } } }Conclusion
Download source
Đọc Ghi File Ms Word Bằng Java Với Apache Poi
Đọc ghi file MS Word bằng Java với Apache POI
Apache POI là một thư viện mã nguồn mở cung cấp bởi apache được sử dụng để xử lý các file office như word, excel, powerpoint…
XWPFDocument:Được sử dụng để đọc ghi các file MS-Word với định dạng .docx (đọc, lưu file, thêm đoạn văn bản…)
XWPFParagraph: Được dùng để tạo đoạn paragraph trong tài liệu word. (Tùy chỉnh căn lề, border)
XWPFRun: Được sử dụng thể thêm text vào paragraph (Tùy chỉnh font, size…)
XWPFTable: Được dùng để thêm mới bảng vào file (Thêm cột, thêm dòng, cài đặt chiều rộng cho cột)
XWPFWordExtractor: Đây là class cơ bản được dùng để lấy text đơn giản từ tài liệu word (lấy tất cả text bên trong file word)
Thư viện sử dụng:
Ví dụ ghi file MS Word:
package stackjava.com.apachepoi.word.demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class DemoWrite { public static void main(String[] args) throws IOException { XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph1 = document.createParagraph(); XWPFRun run = paragraph1.createRun(); run.setText("Paragraph 1: stackjava.com"); XWPFParagraph paragraph2 = document.createParagraph(); run = paragraph2.createRun(); run.setText("Paragraph 2: demo read/write file MS-Word"); FileOutputStream out = new FileOutputStream(new File("demo-apache-apoi-word.docx")); document.write(out); out.close(); document.close(); System.out.println("successully"); } }Kết quả:
package stackjava.com.apachepoi.word.demo; import java.io.FileInputStream; import java.util.List; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; public class DemoRead { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("demo-apache-apoi-word.docx"); XWPFDocument document = new XWPFDocument(OPCPackage.open(fis)); for (XWPFParagraph paragraph : paragraphList) { System.out.println(paragraph.getText()); } System.out.println("=============================="); System.out.println("Read file using XWPFWordExtractor "); XWPFWordExtractor wordExtractor = new XWPFWordExtractor(document); System.out.println(wordExtractor.getText()); wordExtractor.close(); document.close(); } catch (Exception ex) { ex.printStackTrace(); } } }Kết quả:
Paragraph 1: stackjava.com Paragraph 2: demo read/write file MS-Word ============================== Read file using XWPFWordExtractor Paragraph 1: stackjava.com Paragraph 2: demo read/write file MS-WordOkay, Done!
References:
https://poi.apache.org/document/
Functions And Formulas That You Can Use In A Word Document
You can use simple formulas in Microsoft Word, such as addition (+), subtraction (-), multiplication (*), or division (/). Also, you can calculate a power of (^):
See How to reference a cell of a Word table for more details.
All functions you can see in the Paste function drop-down list of the Formula dialog box:
ABS ()
Calculates the absolute value of the value inside the parentheses.
AVERAGE ()
Calculates the average of the elements identified inside the parentheses.
COUNT ()
Calculates the number of elements identified inside the parentheses.
DEFINED ()
Evaluates whether the argument inside parentheses is defined. Returns 1 if the argument has been defined and evaluates without error, 0 if the argument has not been defined or returns an error.
IF ()
Evaluates the first argument. Returns the second argument if the first argument is true; returns the third argument if the first argument is false.
INT ()
Rounds the value inside the parentheses down to the nearest integer.
MAX ()
Returns the maximum value of the items identified inside the parentheses.
MIN ()
Returns the minimum value of the items identified inside the parentheses.
MOD ()
Takes two arguments (must be numbers or evaluate to numbers). Returns the remainder after the second argument is divided by the first. If the remainder is 0 (zero), returns 0.0.
NOT
Evaluates whether the argument is true. Returns 0 if the argument is true, 1 if the argument is false. Mostly used inside an IF formula.
OR ()
Takes two arguments. If both are false, returns 0, else returns 1. Mostly used inside an IF formula.
PRODUCT ()
Calculates the product of items identified inside the parentheses.
ROUND ()
Rounds the first argument to the number of digits specified by the second argument. If the second argument is greater than zero ( 0), first argument is rounded down to the specified number of digits. If second argument is zero ( 0), first argument is rounded down to the nearest integer. If second argument is negative, first argument is rounded down to the left of the decimal.
SIGN ()
Takes one argument that must either be a number or evaluate to a number. Evaluates whether the item identified inside the parentheses if greater than, equal to, or less than zero ( 0). Returns 1 if greater than zero, 0 if zero, -1 if less than zero.
SUM ()
Calculates the sum of items identified inside the parentheses.
The arguments can be:
See also this tip in French: Fonctions et formules dans Word.
Đọc Ghi File Excel Bằng Java Sử Dụng Apache Poi
Đọc ghi file Excel bằng Java sử dụng Apache POI
Apache POI là một thư viện mã nguồn mở cung cấp bởi apache được sử dụng để xử lý các file office như word, excel, powerpoint…
1.1 Xử lý file Excel với Apache POI
Apache POI xử lý các thành phần trong excel theo đúng lập trình hướng đối tượng – mỗi thành phần trong Excel đều được coi như 1 đối tượng.
Các class cơ bản được dùng để đọc ghi file Excel
HSSF: các class có tên bắt đầu là HSSF được dùng để sử lý các file Microsoft Excel 2003 (.xls)
XSSF: các class có tên bắt đầu là XSSF được dùng để sử lý các file Microsoft Excel 2007 trở về sau (.xlsx)
XSSFWorkbook và HSSFWorkbook là các class xử lý với Excel Workbook
HSSFSheet và XSSFSheet là các class xử lý với Excel Worksheet
Row: định nghĩa một dòng trong excel
Cell: định nghĩa một ô trong excel
Ở đây mình sử dụng maven để lấy thư viện của Apache POI.
Cho các file Microsoft Excel 2003
Cho các file Microsoft Excel 2007 trở về sau
3.1 Ghi file Excel
Tạo 1 Worksheet có name là “Customer_Info”
dòng đầu tiên hiển thị “List Of Customer”
Các dòng tiếp theo hiển thị các thông tin của customer (id, name, email), mỗi thông tin ở 1 column.
package stackjava.com.apachepoiexcel.demo; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class WriteFileExcel { public static void main(String[] args) { System.out.println("Create file excel"); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("Customer_Info"); int rowNum = 0; Row firstRow = sheet.createRow(rowNum++); Cell firstCell = firstRow.createCell(0); firstCell.setCellValue("List of Customer"); listOfCustomer.add(new Customer(1, "Sylvester Stallone", "abc@gmail.com")); listOfCustomer.add(new Customer(2, "Tom Cruise", "xyz@yahoo.com")); listOfCustomer.add(new Customer(3, "Vin Diesel", "abc@hotmail.com")); for (Customer customer : listOfCustomer) { Row row = sheet.createRow(rowNum++); Cell cell1 = row.createCell(0); cell1.setCellValue(customer.getId()); Cell cell2 = row.createCell(1); cell2.setCellValue(customer.getName()); Cell cell3 = row.createCell(2); cell3.setCellValue(customer.getEmail()); } try { FileOutputStream outputStream = new FileOutputStream("Demo-ApachePOI-Excel.xlsx"); workbook.write(outputStream); workbook.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Done"); } } package stackjava.com.apachepoiexcel.demo; public class Customer { private int id; private String name; private String email; }Kết quả:
Bây giờ mình sẽ thực hiện đọc lại file Excel vừa tạo ở trên:
package stackjava.com.apachepoiexcel.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadFileExcel { public static void main(String[] args) { try { FileInputStream excelFile = new FileInputStream(new File("Demo-ApachePOI-Excel.xlsx")); Workbook workbook = new XSSFWorkbook(excelFile); Sheet datatypeSheet = workbook.getSheetAt(0); DataFormatter fmt = new DataFormatter(); Row firstRow = iterator.next(); Cell firstCell = firstRow.getCell(0); System.out.println(firstCell.getStringCellValue()); while (iterator.hasNext()) { Row currentRow = iterator.next(); Customer customer = new Customer(); customer.setId(Integer.parseInt(fmt.formatCellValue(currentRow.getCell(0)))); customer.setName(currentRow.getCell(1).getStringCellValue()); customer.setEmail(currentRow.getCell(2).getStringCellValue()); listOfCustomer.add(customer); } for (Customer customer : listOfCustomer) { System.out.println(customer); } workbook.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }*Lưu ý: id của customer là integer nên khi ghi vào file excel nó sẽ là kiểu numeric, do đó khi đọc ra thì nó sẽ đọc là numeric và chuyển thành double, ví dụ 1 sẽ là 1.0. Do đó ta dùng DataFormatter để định dạng nó về kiểu string và parse lại thành integer.
Kết quả:
List of Customer Customer [id=1, name=Sylvester Stallone, email=abc@gmail.com] Customer [id=2, name=Tom Cruise, email=xyz@yahoo.com] Customer [id=3, name=Vin Diesel, email=abc@hotmail.com]Okay, Done!
Đọc ghi file Excel bằng Java sử dụng Apache POI
Reference:
Bạn đang xem bài viết Parse Word Document Using Apache Poi Example trên website Trucbachconcert.com. Hy vọng những thông tin mà chúng tôi đã chia sẻ là hữu ích với bạn. Nếu nội dung hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất. Chúc bạn một ngày tốt lành!