Xu Hướng 3/2023 # Parse Word Document Using Apache Poi Example # Top 8 View | Hoisinhvienqnam.edu.vn

Xu Hướng 3/2023 # Parse Word Document Using Apache Poi Example # Top 8 View

Bạn đang xem bài viết Parse Word Document Using Apache Poi Example được cập nhật mới nhất trên website Hoisinhvienqnam.edu.vn. 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.

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

&ltdependencies&gt &ltdependency&gt &ltgroupId&gt

org.apache.poi

&lt/groupId&gt &ltartifactId&gt

poi-ooxml

&lt/artifactId&gt &ltversion&gt

3.16

&lt/version&gt &lt/dependency&gt &lt/dependencies&gt

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

Thao Tác Với Excel File Bằng Apache Poi

Khi lập trình với bất cứ hệ thống nào thì việc thao tác với các file excel luôn là điều bắt buộc mọi developer phải nắm được. Và để làm việc hiệu quả với excel file trong java thì tôi xin giới thiệu thư viện Apache POI trong bài viết này. POI là viết tắt của Poor Obfuscation Implementation, đó là một thư viện mã nguồn mở của Java, được cung cấp bởi Apache giúp chúng ta làm việc với các tài liệu của Microsoft như Word, Excel, PowerPoint…

Để thao tác với các file Excel thì POI cung cấp cho chúng ta các khái niệm chính sau:

Workbook: Đây là khái niệm đại diện cho một bảng tính, hay một file Excel.

Sheet: tương đương với các sheet trong file Excel, một workbook có thể có một hoặc nhiều sheet.

Row: đơn vị hàng trong một bảng tính

Cell: đại diện cho một cột trong bảng tính. Như vậy mỗi một ô trong file Excel sẽ được biểu diễn bằng một row và một cell.

Để làm việc với Excel thì chúng ta không cần quan tâm đến tất cả các class trong thư viện POI mà chỉ cần để ý đến 2 loại sau:

Các class có tiếp đầu ngữ là HSSF (Horrible SpreadSheet Format) : Các class giúp đọc và ghi file dang Microsoft Excel (XLS – dạng excel cũ). Ví dụ: HSSFWorkbook, HSSFSheet, HSSFCellStyle,…

Các class có tiếp đầu ngữ là XSSF (XML SpereadSheet Format) : Đọc và ghi định dạng file Open Office XML (XLSX – dạng excel mới).

Nếu bạn sử dụng Maven thì cần thêm dependency của POI vào file pom.xml:

Còn Gradle thì thêm vào build.gradle:

compile "org.apache.poi:poi:3.17"

Trước tiên, ta tạo một class model để có thể ghi các ra các row theo một List data:

public class Employee { private String name; private String email; private Date dateOfBirth; private double daysOfWork; private double salaryPerDay; private Double totalSalary; public Employee(String name, String email, Date dateOfBirth, double daysOfWork, double salaryPerDay, Double totalSalary) { chúng tôi = name; this.email = email; this.dateOfBirth = dateOfBirth; this.daysOfWork = daysOfWork; this.salaryPerDay = salaryPerDay; this.totalSalary = totalSalary; }

Tiếp đến chuẩn bị data raw để ghi vào file excel:

Sau các bước chuẩn bị data, chúng ta tạo một workbook:

Có workbook rồi chúng ta tạo tiếp một sheet trong đó:

Có thể thêm một chút màu sắc font bạt cho đẹp mắt:

Font headerFont = workbook.createFont(); headerFont.setBold(true); headerFont.setFontHeightInPoints((short) 14); headerFont.setColor(IndexedColors.RED.getIndex());

Sau đó chúng ta tạo row đầu tiên chứa các tiêu đề của các cột:

Do trong phần model của chúng ta có loại dữ liệu khác đặc biệt là Date (dateOfBirth) nên chúng ta cần một format cho nó:

Tiếp đến là công việc chính, set data vào các ô trong file excel:

Chú ý rằng cột cuối cùng ta dùng công thức để tính tổng lương của mỗi nhân viên nên CellType ở đây sẽ là FORMULA.

Cuối cùng là ghi tất cả ra một file Excel thật và kết thúc việc tạo một file Excel:

Nội dung file employee.xlsx sẽ như sau:

Để đọc một file Excel có sẵn, đầu tiên chúng ta cũng tạo một workbook cho file đó:

Duyệt các sheet trong một workbook:

Vì trong file excel ta vừa tạo chỉ có một sheet nên chúng ta sẽ get nó ra như sau:

Để duyệt các row trong sheet, ta làm như sau:

Sau khi duyệt xong nhớ đóng workbook lại:

Màn hình console sẽ trông như sau:

Từ đây ta có thể nhận thấy đối với kiểu là FORMULA thì khi in ra chúng ta sẽ nhận được công thức của field đó chứ không phải giá trị cuối cùng. Để nhận các giá trị cuối cùng của field thì chúng ta viết thêm hàm sau:

private static Object getCellValue(Cell cell, FormulaEvaluator evaluator) { CellValue cellValue = evaluator.evaluate(cell); switch (cellValue.getCellTypeEnum()) { case BOOLEAN: return cellValue.getBooleanValue(); case NUMERIC: return cellValue.getNumberValue(); case STRING: return cellValue.getStringValue(); case BLANK: return ""; case ERROR: return cellValue.getError(cell.getErrorCellValue()).getStringValue();

Với một cell có kiểu FORMULA bạn có thể in ra công thức của nó và sử dụng FormulaEvaluator để tính toán giá trị của ô cho bởi công thức đó. Sau đó sửa lại đoạn duyệt row như sau:

Kết quả nhận được sẽ như sau:

Để sửa một file Excel thì chúng ta cũng làm tương tự đọc một file Excel. Đầu tiên là tạo một workbook cho nó và một sheet tương ứng:

Workbook workbook = WorkbookFactory.create(new File("./employee.xlsx");

Xác định vị trí cần update lại và định vị nó. Cần chú ý nếu vị trí cần update chưa được tạo thì cần khởi tạo field đó trước, nếu không chương trình sẽ throw một Exception:

Update lại định dạng và giá trị của field đó:

Output ra một file Excel khác và đóng workbook:

https://github.com/tubean/apache-poi-tutorial.git

https://www.callicoder.com/java-write-excel-file-apache-poi/https://www.callicoder.com/java-read-excel-file-apache-poi/

How To Use Find And Replace In Microsoft Word To Make Quick Edits To A Document

Find and Replace in Word is a tool that searches a document for a specific word or phrase.

You can use the tool to replace a word or phrase with another.

You can review each instance of a word before replacing it, or replace all instances at once.

Visit Insider’s Tech Reference library for more stories

10 Things in Tech: Get the latest tech trends & innovations

Loading Something is loading.

Email address

Locate the find and replace option in the “Edit” tab.

Marissa Perino/Insider

Find and replace.

Marissa Perino/Insider

Open “Advanced Find and Replace…”

Marissa Perino/Insider

Choose an option from the “Format” dropdown.

Marissa Perino/Insider

Marissa Perino/Insider

Whatever alterations you make, the pop-up will list your formatting changes under “Replace with.”

Choose to replace the first match, replace all, or find the next.

A pop-up will appear when replacements are complete.

You can replace matching words straight from this menu.

Marissa Perino/Insider

Fill in the slots with the appropriate words.

Abigail Abesamis Demarest/Insider

Abigail Abesamis Demarest/Insider

Thao Tác Với File Excel Trong Java Sử Dụng Api Apache Poi

Đôi điều về Apache POI

Nhiều khi trong một ứng dụng phần mềm cần thiết phải tạo ra các báo cáo trong định dạng file Microsoft Excel, hoặc sẽ nhận file Excel như dữ liệu đầu vào. Ví dụ, một ứng dụng được phát triển cho bộ phận Tài chính của một công ty sẽ được yêu cầu để tạo ra tất cả các kết quả đầu ra là file Excel. Bất kỳ lập trình viên Java nào muốn sản xuất các tập tin MS Office như đầu ra thì nên sử dụng một giao diện lập trình(API) để làm như vậy. Apache POI là một API cho phép lập trình viên tạo mới, sửa và hiển thị Microsoft Office file sử dụng Java. Apache POI là một thư viện mã nguồn mở được phát triển và xuất bản bởi Apache Software Foundation.

Cấu phần của Apache POI

Apache POI chứa các lớp và phương thức để làm việc trên các tài liệu dưới định dạng file MS Office. Danh sách các thành phần của API như sau.

POIFS (Poor Obfuscation Implementation File System) : This component is the basic factor of all other POI elements. It is used to read different files explicitly.

HPSF (Horrible Property Set Format) : Được sử dụng để trích xuất các thuộc tính của file MS-Office.

HWPF (Horrible Word Processor Format) : Được sử dụng để đọc ghi định dạng .doc của file MS-Office.

XWPF (XML Word Processor Format) : Được sử dụng để đọc ghi định dạng .docx của file MS-Office.

HSLF (Horrible Slide Layout Format) : Được sử dụng để đọc ghi file PowerPoint.

HDGF (Horrible DiaGram Format) : Được sử dụng cho file MS-Visio dưới dạng binary.

HPBF (Horrible PuBlisher Format) : Được sử dụng để đọc ghi file MS-Publisher.

Note

Các phiên bản cũ của Apache POI chỉ hỗ trợ các định dạng file binary như doc, xls, ppt, vv từ phiên bản 3.5 trở đi, POI hỗ trợ các định dạng file OOXML của MS-Office như docx, xlsx, pptx, vv

Làm việc với MS-Excel

Excel là định dạng file rất phổ biến được tạo bởi Microsoft. Mặc dù nó không phải là định dạng file mở nhưng ứng dụng Java vẫn có thể đọc, ghi Excel file bằng cách sử dụng giao diện lập trình Apache POI.

Cách thức lấy thư viện Apache POI Để sử dụng POI cho ứng dụng của bạn, có 2 cách:

Cho ứng dụng Maven: Thêm các dependency sau vào file pom.xml:

Chúng ta sẽ sử dụng entity Book để đọc ghi dữ liệu

package vuta.apache.poi.example; public class Book { private String title; private String author; private double price; public Book() { } public Book(String title, String author, double price) { super(); this.title = title; this.author = author; this.price = price; } public String toString() { return String.format("%s - %s - %f", title, author, price); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }

Cập nhật thông tin chi tiết về Parse Word Document Using Apache Poi Example trên website Hoisinhvienqnam.edu.vn. 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. Chúc bạn một ngày tốt lành!