Xu Hướng 6/2023 # Thao Tác Với Excel File Bằng Apache Poi # Top 13 View | Hoisinhvienqnam.edu.vn

Xu Hướng 6/2023 # Thao Tác Với Excel File Bằng Apache Poi # Top 13 View

Bạn đang xem bài viết Thao Tác Với Excel File Bằng Apache Poi đượ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.

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/

Đọ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:

Đọc Ghi File Excel Trong Java Sử Dụng Apache Poi

1- Apache POI là gì?

Apache POI là một thư viện mã nguồn mở Java, được cung cấp bởi Apache, nó là một thư viện đầy sức mạnh giúp bạn làm việc với các tài liệu của Microsoft như Word, Excel, Power point, Visio,…

POI là viết tắt của“Poor Obfuscation Implementation”. Các định dạng file của Microsoft được giấu kín. Những kỹ sư của Apache phải cố gắng để tìm hiểu nó, và họ thấy rằng Microsoft đã tạo ra các định dạng phức tạp một cách không cần thiết. Và cái tên thư viện bắt nguồn từ sự hài ước.

Poor Obfuscation Implementation: Sự thực hiện cái nghèo nàn ngu muội. (Tạm dịch là vậy).

Trong tài liệu này tôi hướng dẫn các bạn sử dụng Apache POI để làm việc với Excel.

Apache POI hỗ trợ bạn làm việc với các định dạng của Microsoft, các class của nó thường có tiếp đầu ngữ HSSF, XSSF, HPSF, … Nhìn vào tiếp đầu ngữ của một class bạn có thể biết được class đó hỗ trợ loại định dạng nào.

Chẳng hạn để làm việc với các định dạng Excel (XLS) bạn cần các class:

HSSFWorkbook

HSSFSheet

HSSFCellStyle

HSSFDataFormat

HSSFFont

Apache POI cung cấp cho bạn các interfaceWorkbook,Sheet,Row,Cell,… và các class thể hiện (implementation) tương ứng là HSSFWorkbook, HSSFSheet, HSSFRow, HSSFCell,…

Nếu project của bạn sử dụng Maven, bạn chỉ cần khai báo thư viện một cách đơn giản trong chúng tôi :

Nếu bạn không sử dụng Maven bạn có thể download thư viện Apache POI tại:

Download về và giải nén, để làm việc với Excel bạn cần ít nhất 3 file jar:

poi-**.jar

lib/commons-codec-**.jar

lib/commons-collections4-**.jar

Trong tài liệu này, tôi tạo một Project Maven đơn giản có tên ApachePOIExcel

Group ID: org.o7planning

Artifact ID: ApachePOIExcel

Microsoft Office các phiên bản trước đây (97-2003) các file excel có định dạng XLS và các phiên bản mới thường sử dụng định dạng XSLX. Để thao tác với các file XSL bạn cần sử dụng các class có tiếp đầu ngữ HSSF. Còn đối với các file định dạng XSLX cần sử dụng các class có tiếp đầu ngữ XSSF.

Chú ý: Trong tài liệu này tôi đang sử dụng Apache POI 3.15, API có nhiều thay đổi so với phiên bản cũ hơn. Có nhiều phương thức sẽ bị loại bỏ trong phiên bản tương lai (Apache POI 4.x). POI đang hướng tới sử dụng Enum thay thế cho các hằng số trong API của nó.

7- Cập nhập file Excel có sẵn

Trong ví dụ này, tôi đọc file excel chúng tôi và cập nhập các giá trị cho cột Salary tăng lên 2 lần.

Kết quả sau khi cập nhập:

Nếu bạn có kiến thức về Excel, sẽ không khó để bạn thiết lập một công thức. Với Apache POI bạn có thể tạo một Cell có kiểu CellType.FORMULA, giá trị của nó được tính dựa trên một công thức.

SUM

Ví dụ: Tính tổng các ô trên cùng cột “C” từ dòng thứ 2 tới dòng thứ 4:

cell = row.createCell(rowIndex, CellType.FORMULA); cell.setCellFormula("SUM(C2:C4)");

Công thức từ các ô riêng lẻ:

cell = row.createCell(rowIndex, CellType.FORMULA); cell.setCellFormula("0.1*C2*D3");

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 đó.

String formula = cell.getCellFormula(); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); CellValue cellValue = evaluator.evaluate(cell); double value = cellValue.getNumberValue(); String value = cellValue.getStringValue(); boolean value = cellValue.getBooleanValue();

Parse Word Document Using Apache Poi Example

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

Cập nhật thông tin chi tiết về Thao Tác Với Excel File Bằng Apache Poi 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!