Bạn đang xem bài viết Đọc Ghi Excel File Sử Dụ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.
Do vậy, trong bài viết này, mình đã giới thiệu về Apache POI là một thư viện mã nguồn mở cho phép chúng ta thao tác với các tập tin định dạng microsoft office. Trong bài viết này chúng ta sẽ cùng nhau tìm hiểu cách đọc và ghi excel file sử dụng Apache POI.
Maven denpendency
Để thao tác được với Excel file, chúng ta cần thêm các denpendency cần thiết.
Một số lưu ý khi sử dụng Apache POI
Bài viết này sẽ hướng dẫn các bạn cách đọc và ghi file excel sử dụng thư viện Apache POI. Tuy nhiên có một số lưu ý sau các bạn cần chú ý để có thể triển khai cho từng trường hợp của mình.
Tiền tố HSSF được đặt trước các tên class dùng để thao tác với các file định dạng Microsoft Excel 2003.
Tiền tố XSFF được đặt trước các tên class dùng để thao tác với các file định dạng Microsoft Excel 2007.
XSSFWorkbook và HSSFWorkbook là các class đại diện cho một excel workbook.
HSSFSheet và XSSFSheet là các class đại diện cho một excel WorkSheet.
Row đại diện cho một dòng.
Cell đại diện cho một ô trong một hàng xác định.
Trong bài hướng dẫn này, các bạn sẽ được hướng dẫn cách đọc ghi file excel Microsoft Excel 2007 có đôi là xlsx, có nghĩa là chúng ta sẽ sử dụng các class có tiền tố là XSFF để đọc file exel.
Ghi excel file
Để ghi một excel file cần qua những bước cơ bản sau:
Tạo workbook.
Tạo một sheet trong workbook.
Tạo một dòng trong sheet.
Thêm một cột trong sheet.
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; import java.io.File; import java.io.FileOutputStream; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main { public static void main(String[] args) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("student Details"); data.put("1", new Object[]{"ID", "NAME", "LASTNAME"}); data.put("2", new Object[]{1, "Pankaj", "Kumar"}); data.put("3", new Object[]{2, "Prakashni", "Yadav"}); data.put("4", new Object[]{3, "Ayan", "Mondal"}); data.put("5", new Object[]{4, "Virat", "kohli"}); int rownum = 0; for (String key : keyset) { Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String) obj); else if (obj instanceof Integer) cell.setCellValue((Integer) obj); } } try { FileOutputStream out = new FileOutputStream(new File("gfgcontribute.xlsx")); workbook.write(out); out.close(); System.out.println("gfgcontribute.xlsx written successfully on disk."); } catch (Exception e) { e.printStackTrace(); } } }Đọc file excel
Để đọc một excel file chúng ta cũng có các bước sau:
Khởi tạo một workbook instance từ excel file.
Lấy sheet từ workbook.
Đọc từng dòng, mỗi dòng lấy giá trị từ từng cột.
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; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; public class Main { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("gfgcontribute.xlsx")); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); while (rowIterator.hasNext()) { Row row = rowIterator.next(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "t"); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "t"); break; } } System.out.println(""); } file.close(); } catch (Exception e) { e.printStackTrace(); } } }Output:
IDtNAMEtLASTNAMEt1.0tPankajtKumart2.0tPrakashnitYadavt3.0tAyantMondalt4.0tVirattkohlit
Note: Nếu bạn muốn đọc một file tại một đường dẫn khác, thì bạn chỉ việc thay
FileInputStream file = new FileInputStream(new File("gfgcontribute.xlsx"));thành đường dẫn bạn mong muốn.
Thêm dữ liệu vào sheet
Nếu bạn đã có một excel sẵn và muốn ghi thêm dự liệu vào đó, thì chỉ cần lấy sheet đó ra từ workbook, đi đến dòng cuối cùng và bắt đầu ghi thêm dữ liệu vào.
private static final String FILE_NAME = "C:\Users\pankaj\Desktop\projectOutput\blo.xlsx"; public static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); int num = sheet.getLastRowNum(); Row row = sheet.createRow(++num); row.createCell(0).setCellValue("xyz"); ..... .. FileOutputStream fileOut = new FileOutputStream(FILE_NAME); wb.write(fileOut); fileOut.close(); }Nguồn tham khảo
https://www.geeksforgeeks.org/reading-writing-data-excel-file-using-apache-poi/
Sử Dụng Apache Poi Để Đọc, Ghi Dữ Liệu Từ File Excel Trong Selenium
Vậy thì vấn đề đặt ra ở đây là, nếu như dữ liệu cần phải thay đổi nhiều lần, liên tục và hàng ngày thì chúng ta sẽ thực hiện thay đổi từng phần theo mỗi lần thay đổi đó và rồi lại biên dịch lại? Chỉ nghĩ thôi đã thấy khá là mệt mỏi rồi, chưa kể đến việc biên dịch lỗi và ngồi mần lại thì đúng là ác mộng.
Thế nên trải qua rất nhiều kinh nghiệm xương máu, người ta và người tây đã rút ra được rằng, việc phát triển code tốt nhất là nên tách rời với phần dữ liệu để khi hoạt động chúng không ảnh hưởng đến nhau đến các file chương trình. Đưa dữ liệu ra ngoài các file code của chương trình chính là cách duy nhất để làm việc đó, chúng ta có thể đưa dữ liệu vào trong các file excel, property file, config file, Json file, hay các XML file…
1. Về Apache POI
Các bước thực hiện download Apache POI
1. Truy cập link: https://poi.apache.org/download.html
3. Lưu file zip về máy tính, sau đó giải nén ta được một folder và các thông tin tương tự như hình dưới:
Vậy là xong bước download bộ thư viện Apache POI.
2. Tích hợp Apache POI và Selenium Webdriver
Chúng ta có thể sử dụng tích hợp Apache POI trong Selennium Webdriver để thực hiện đọc và ghi file excel và tạo một data drivent framework.
Các bước để thực hiện tích hợp Apache POI với project Selenium webdriver:
1. Mở project selenium webdriver trên Eclipse
3. Nhấn vào nút Add External jars
4. Thực hiện điều hướng đến thư mục chứa Apache POI vừa giản nén, chọn các file jars trong thư mục chính, các file jar trong thư mục lib, và trong thư mục ooxml-lib:
3. Một số thuật ngữ quan trọng thường dùng trong Apache POI
Thư viện của Apache POI xoay quanh 4 từ khóa quen thuộc trong một file excel:
Workbook: 1 workbook đại diện cho 1 file excel
Sheet: 1 workbook có thể bao gồm nhiều sheet, chúng ta có thể truy cập vào các sheet này dựa theo tên hoặc chỉ số (index) của sheet đó trong workbook.
Row: như tên gọi của nó, đại diện cho một hàng của 1 sheet.
Cell: một cell sẽ đại diện cho một ô trong sheet.
4. Đọc dữ liệu file excel với Apache POI
Trước tiên chúng ta sẽ cùng thực hiện đọc dữ liệu từ 1 file excel và in ra màn hình nội dung đó.
1. Tạo project, và class trong Eclipse
2. Tạo 1 file excel có tên là testData.xlsx, có 1 sheet tên là Sheet1 và nội dung của ô A1 = Hello. Lưu lại trong một thư mục ở máy tính của bạn.
3. Tạo một đối tượng cho FileInputStream chứa đường dẫn đến nơi lưu trữ file data excel:
4. Tạo đối tượng workbook bằng cách sử dụng method create() trong WorkbookFactory class và truyền vào đó tham số đầu vào là đối tượng fis file excel ta vừa tạo ở bước 3:
5. Tạo đối tượng sheet từ đối tượng workbook (wb) vừa tạo ở bước 4, ở đây ta sẽ truyền tham số đầu vào chính xác tên của sheet trong file excel ta đã chuẩn bị ở bước 2 là Sheet1:
6. Tạo đối tượng Row từ sheet vừa có ở bước 5, tham số đầu vào là chỉ số hàng – bắt đầu từ 0
7. Ta cũng có thể tạo 1 đối tượng cell từ đối tượng row ở bước 6, tham số đầu vào ở đây cũng là chỉ số cell:
8. Để lấy ra giá trị của ô trong file excel ta có thể gọi method getStringCellValue() trong cell class:
5. Ghi dữ liệu vào file excel trong Selenium Webdriver
7. Tạo một cell thuộc row với tham số đầu vào là chỉ số của cell muốn thêm:
8. Thực hiện gán giá trị cho cell đó bằng cách sử dụng method setCellValue() trong Cell Class:
9. Tạo đối tượng để lưu thông tin file output với FileOutputStream :
10. Method write() sẽ giúp chúng ta thực hiện lưu thông tin giá trị vừa gán vào trong file với đối tượng fos:
Để đọc thì đơn giản là ta sẽ cần sử dụng vòng lặp for với biến i,j tương ứng cho hàng và cột cứ thế thì sẽ ra thôi. Kaka. Nói thì dễ nhưng làm rồi mới thấy dễ hơn =)))
Thông thường, đọc và ghi dữ liệu file excel mình sẽ viết thành một hàm và cho nó vào 1 file common nào đó, khi nào cần thì sẽ gọi ra và dùng thôi.
import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelCommon_POI { private static XSSFSheet ExcelWSheet; private static XSSFWorkbook ExcelWBook; private static XSSFCell Cell; public static XSSFSheet setExcelFile(String Path, String SheetName) throws Exception { try { FileInputStream ExcelFile = new FileInputStream(Path); ExcelWBook = new XSSFWorkbook(ExcelFile); ExcelWSheet = ExcelWBook.getSheet(SheetName); } catch (Exception e) { throw (e); } return ExcelWSheet; } public static String getCellData(int RowNum, int ColNum, XSSFSheet excelWSheet) throws Exception { try { Cell = excelWSheet.getRow(RowNum).getCell(ColNum); String CellData = Cell.getStringCellValue(); return CellData; } catch (Exception e) { return ""; } } public static void writeDataToExcel(int rowcount, int columncount, String filepath, String Sheetname, String value) { try { FileInputStream input = new FileInputStream(filepath); XSSFWorkbook wb = new XSSFWorkbook(input); XSSFSheet sh = wb.getSheet(Sheetname); XSSFRow row = sh.getRow(rowcount); FileOutputStream webdata = new FileOutputStream(filepath); row.createCell(columncount).setCellValue(value); wb.write(webdata); } catch (Exception e) { } } }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; } }Hướng Dẫn Xuất Dữ Liệu Lớn Ra File Excel Với Thư Viện Apache Poi
Trong bài viết trước, tôi đã hướng dẫn đọc và ghi file excel trong Java sử dụng thư viện Apache POI. Với lượng dữ liệu ít khoảng vài nghìn dòng trở lại, khi xuất excel và .xlsx chúng ta có thể sử dụng các lớp có tiếp đầu ngữ HSSF, XSSF để xuất dữ liệu ra file excel mà không ảnh hưởng nhiều đến hiệu suất của chương trình. Tuy nhiên, với dữ liệu rất lớn khoảng vài chục nghìn dòng trở lên thì thời gian xử lý sẽ tương đối chậm, tốn nhiều bộ nhớ. May mắn là thư viện Apache POI còn thêm một class khác là SXSSF giúp chúng ta giải quyết vấn đề này.
SXSSF (Streaming version of XSSFWorkbook) là một phần mở rộng API của XSSF, được sử dụng khi xuất các file excel lớn và có bộ nhớ heap sapce hạn chế. Do SXSSF mở rộng từ XSSF nên chỉ hỗ trợ xuất file có phần mở rộng là .xlsx ( Microsoft Excel 2007 trở về sau).
Trong phần tiếp theo của bài này, tôi sẽ hướng dẫn các bạn đọc và ghi file excel sử dụng lớp có tiếp đầu ngữ là SXSSF. Nếu bạn chưa biết cách xuất dữ liệu ra file excel sử dụng thư viện Apache POI thì hãy xem bài viết Hướng dẫn đọc và ghi file excel trong Java sử dụng thư viện Apache POI.
Để tiện theo dõi, tôi sẽ sử dụng lại ví dụ của bài viết trước, chỉ thay đổi các lớp có tiếp đầu ngữ HSSF, XSSF bằng SXSSF.
Khởi tạo SXSSF
Trước khi đi vào phần ví dụ, chúng ta hãy tìm hiểu cách khởi tạo SXSSF:
SXSSFWorkbook workbook = new SXSSFWorkbook(); SXSSFWorkbook workbook = new SXSSFWorkbook(50); SXSSFWorkbook workbook = new SXSSFWorkbook(-1);Lưu ý:
rowAccessWindowSize : xác định số lượng hàng (row) có thể được truy cập nhiều nhất thông qua SXSSFSheet.getRow. Khi một hàng (row) mới được tạo ra thông qua SXSSFSheet.createRow và nếu tổng số các bản ghi vượt quá giá trị được chỉ định (rowAccessWindowSize), khi đó hàng (row) với giá trị chỉ mục thấp nhất sẽ được làm mới (flushed) và không thể được truy cập thông qua SXSSFSheet.getRow nữa.
Các thao tác trên SXSSF như: createRow, getRow, autoSizeColumn, … chỉ ảnh hưởng đến các record trong phạm vi rowAccessWindowSize được chỉ định.
Phương thức autoSizeColumn: chỉ tự động điều chỉnh cỡ trong phạm vi rowAccessWindowSize được chỉ định. Để có thể autoSizeColumn đúng trên tất cả các record, cần đánh dấu theo dõi các cột trong bảng để tự động điều chỉnh định cỡ. Việc xác định độ rộng phù hợp nhất cho một ô rất đắt, điều này có thể ảnh hưởng đến hiệu suất chương trình.
sheet.trackColumnForAutoSizing(columnIndex); sheet.trackAllColumnsForAutoSizing();Ví dụ sử dụng SXSSF
Book.java
package com.gpcoder.apachepoi; public class Book { private Integer id; private String title; private Integer quantity; private Double price; private Double totalMoney; public Book() { super(); } public Book(Integer id, String title, Integer quantity, double price) { super(); this.id = id; this.title = title; this.quantity = quantity; this.price = price; } @Override public String toString() { return "Book [id=" + id + ", title=" + title + ", quantity=" + quantity + ", price=" + price + ", totalMoney=" + totalMoney + "]"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Double getTotalMoney() { return totalMoney; } public void setTotalMoney(Double totalMoney) { this.totalMoney = totalMoney; } }WriteExcelUsingSXSSF.java
package com.gpcoder.apachepoi; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.BuiltinFormats; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; public class WriteExcelUsingSXSSF { public static final int COLUMN_INDEX_ID = 0; public static final int COLUMN_INDEX_TITLE = 1; public static final int COLUMN_INDEX_PRICE = 2; public static final int COLUMN_INDEX_QUANTITY = 3; public static final int COLUMN_INDEX_TOTAL = 4; private static CellStyle cellStyleFormatNumber = null; public static void main(String[] args) throws IOException { final String excelFilePath = "C:/demo/books_large.xlsx"; writeExcel(books, excelFilePath); } SXSSFWorkbook workbook = new SXSSFWorkbook(); SXSSFSheet sheet = workbook.createSheet("Books"); sheet.trackAllColumnsForAutoSizing(); int rowIndex = 0; writeHeader(sheet, rowIndex); rowIndex++; for (Book book : books) { SXSSFRow row = sheet.createRow(rowIndex); writeBook(book, row); rowIndex++; } writeFooter(sheet, rowIndex); int numberOfColumn = 5; autosizeColumn(sheet, numberOfColumn); createOutputFile(workbook, excelFilePath); System.out.println("Done!!!"); } Book book; for (int i = 1; i <= 5; i++) { book = new Book(i, "Book " + i, i * 2, i * 1000); listBook.add(book); } return listBook; } private static void writeHeader(SXSSFSheet sheet, int rowIndex) { CellStyle cellStyle = createStyleForHeader(sheet); SXSSFRow row = sheet.createRow(rowIndex); SXSSFCell cell = row.createCell(COLUMN_INDEX_ID); cell.setCellStyle(cellStyle); cell.setCellValue("Id"); cell = row.createCell(COLUMN_INDEX_TITLE); cell.setCellStyle(cellStyle); cell.setCellValue("Title"); cell = row.createCell(COLUMN_INDEX_PRICE); cell.setCellStyle(cellStyle); cell.setCellValue("Price"); cell = row.createCell(COLUMN_INDEX_QUANTITY); cell.setCellStyle(cellStyle); cell.setCellValue("Quantity"); cell = row.createCell(COLUMN_INDEX_TOTAL); cell.setCellStyle(cellStyle); cell.setCellValue("Total money"); } private static void writeBook(Book book, SXSSFRow row) { if (cellStyleFormatNumber == null) { short format = (short) BuiltinFormats.getBuiltinFormat("#,##0"); SXSSFWorkbook workbook = row.getSheet().getWorkbook(); cellStyleFormatNumber = workbook.createCellStyle(); cellStyleFormatNumber.setDataFormat(format); } SXSSFCell cell = row.createCell(COLUMN_INDEX_ID); cell.setCellValue(book.getId()); cell = row.createCell(COLUMN_INDEX_TITLE); cell.setCellValue(book.getTitle()); cell = row.createCell(COLUMN_INDEX_PRICE); cell.setCellValue(book.getPrice()); cell.setCellStyle(cellStyleFormatNumber); cell = row.createCell(COLUMN_INDEX_QUANTITY); cell.setCellValue(book.getQuantity()); cell = row.createCell(COLUMN_INDEX_TOTAL, CellType.FORMULA); cell.setCellStyle(cellStyleFormatNumber); int currentRow = row.getRowNum() + 1; String columnPrice = CellReference.convertNumToColString(COLUMN_INDEX_PRICE); String columnQuantity = CellReference.convertNumToColString(COLUMN_INDEX_QUANTITY); cell.setCellFormula(columnPrice + currentRow + "*" + columnQuantity + currentRow); } private static CellStyle createStyleForHeader(Sheet sheet) { Font font = sheet.getWorkbook().createFont(); font.setFontName("Times New Roman"); font.setBold(true); font.setFontHeightInPoints((short) 14); font.setColor(IndexedColors.WHITE.getIndex()); CellStyle cellStyle = sheet.getWorkbook().createCellStyle(); cellStyle.setFont(font); cellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex()); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellStyle.setBorderBottom(BorderStyle.THIN); return cellStyle; } private static void writeFooter(SXSSFSheet sheet, int rowIndex) { SXSSFRow row = sheet.createRow(rowIndex); SXSSFCell cell = row.createCell(COLUMN_INDEX_TOTAL, CellType.FORMULA); cell.setCellFormula("SUM(E2:E6)"); } private static void autosizeColumn(SXSSFSheet sheet, int lastColumn) { for (int columnIndex = 0; columnIndex < lastColumn; columnIndex++) { sheet.autoSizeColumn(columnIndex); } } private static void createOutputFile(SXSSFWorkbook workbook, String excelFilePath) throws IOException { try (OutputStream os = new FileOutputStream(excelFilePath)) { workbook.write(os); } } }Thực thi chương trình trên, một file books_large.xlsx được tạo ra trong thư mục C:/demo như sau:
So sánh hiệu xuất chương trình khi sử dụng SXSSF và XSSF
Để so sánh hiệu suất của chương trình khi sử dụng SXSSF và XSSf, tôi sử dụng lại ví dụ WriteExcelUsingSXSSF ở trên, và ví dụ WriteExcelExample ở bài viết trước.
Trong ví dụ bên dưới, tôi sử dụng lớp StopWatch của thư viện Apache Common Lang để đo thời gian thực thi của chương trình
Bây giờ, hãy tăng số lượng dữ liệu cần xuất ra khoảng 100.000 dòng (thay đổi trong phương thức getBooks). Xem kết quả thực thi của 2 chương trình như sau:
Bây giờ hãy thử xóa bỏ các đoạn code autoresize column ở 2 chương trình, vẫn kiểm tra 100.000 record.
WriteExcelUsingSXSSF:
Kết quả thực thi chương trình trên:
Kết quả thực thi chương trình trên:
Khi cần xuất dữ liệu lớn ra file .xlsx và không có yêu cầu về autoresize column thì nên sử dụng SXSSF để đạt được hiệu suất tốt hơn.
Cám ơn các bạn đã quan tâm và theo dõi bài viết, hẹn gặp lại ở các bài viết tiếp theo.
Cập nhật thông tin chi tiết về Đọc Ghi Excel File Sử Dụ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!