Top 8 # Xuất Dữ Liệu Ra File Excel Trong Java Xem Nhiều Nhất, Mới Nhất 3/2023 # Top Trend | Trucbachconcert.com

Java: Cách Tạo Và Chèn Dữ Liệu Vào File Excel

Trong Java, việc đọc tệp excel và ghi tệp excel có một chút khó khăn vì trang tính Excel có các ô để lưu trữ dữ liệu. Java không cung cấp API trực tiếp để đọc hoặc viết các tài liệu Microsoft Excel hoặc Word. Ta sẽ phải dựa vào thư viện của bên thứ ba là Apache POI. Trong phần này, chúng ta sẽ học cách tạo một tệp excel bằng Java và cách ghi hoặc chèn dữ liệu vào tệp excel bằng thư viện Apache POI Java.

1. Thư viện POI Java Apache

Apache POI (Thực hiện giải mã kém) là một API Java để đọc và ghi Tài liệu Microsoft. Nó chứa các lớp và giao diện. Thư viện Apache POI cung cấp hai cách triển khai để đọc hoặc ghi tệp excel:

Triển khai HSSF (Horrible SpreadSheet Format): Nó biểu thị một API đang hoạt động với Excel 2003 hoặc các phiên bản cũ hơn.

Triển khai XSSF (XML SpreadSheet Format): Nó biểu thị một API đang hoạt động với phiên bản Excel 2007 trở lên.

Trong phần này sẽ sẽ sử dụng triển khai HSSF.

2. Tạo file Excel trong Java

Bước 1: Tạo một dự án Java với tên CreateExcelFile từ IntelliJ.

Bước 2: Tạo một lớp tên CreateExcelFileExample1.

Bước 2: Tải xuống thư viện Apache POI ( poi-3.17.jar).

Bước 5: Nhấp chọn Libraries sau đó nhấn dấu + và chọn Java như hình dưới:

Bước 6: Tìm đến nơi chứa file chúng tôi rồi chọn và nhấp vào nút OK. Điều này sẽ thêm tệp JAR vào dự án. Sau đó, nhấp vào nút Apply để áp dụng các thay đổi rồi nhấn nút OK.

Sau khi đã hoàn thành tất cả các bước trên, cấu trúc dự án sẽ giống như sau:

Giờ ta sẽ tiếp tục với các đoạn mã:

Trong chương trình sau, ta sử dụng thư viện Apache POI để tạo một file excel. Thư viện cung cấp lớp có tên HSSFWorkbook được định nghĩa trong gói org.apache.poi.hssf.usermodel.

CreateExcelFileExample1.java ​

import java.io.*; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; public class CreateExcelFileExample1 { public static void main(String[] args) throws IOException {

Kết quả:

“C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1jbrbinjava.exe” “-javaagent:C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1libidea_rt.jar=58544:C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1bin” -Dfile.encoding=UTF-8 -classpath E:CoursesJavaCreateExcelFileoutproductionCreateExcelFile;E:CoursesJavaCreateExcelFilepoi-3.17.jar CreateExcelFileExample1 File Excel đã được tạo thành công.

Ta đã tạo được một file excel trống tại vị trí được chỉ định.

Giờ ta tạo một chương trình Java khác để tạo một tệp excel.

CreateExcelFileExample2.java​

import java.io.*; public class CreateExcelFileExample2 { public static void main(String[] args) { try { String filename = "C: \ Users \ Anubhav \ Desktop \ CustomersDetail.xlsx"; FileOutputStream fileOut = new FileOutputStream(filename); fileOut.close(); System.out.println("File Excel được tạo thành công."); } catch (Exception e) { e.printStackTrace(); } } }

Kết quả:

“C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1jbrbinjava.exe” “-javaagent:C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1libidea_rt.jar=58581:C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1bin” -Dfile.encoding=UTF-8 -classpath E:CoursesJavaCreateExcelFileoutproductionCreateExcelFile;E:CoursesJavaCreateExcelFilepoi-3.17.jar CreateExcelFileExample2 File Excel được tạo thành công.

Ta đã tạo được một tệp excel trống tại vị trí được chỉ định.

3. Tạo và chèn dữ liệu vào file Excel

CreateExcelFileExample3.java

import java.io.*; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFRow; public class CreateExcelFileExample3 { public static void main(String[] args) { try { ""//khai báo tên file muốn tạo String filename = "E: \ Courses \ Java \ CreateExcelFile \ Excel3.xlsx";//tạo một đối tượng của lớp HSSFWorkbook HSSFWorkbook workbook = new HSSFWorkbook();//gọi phương thức creatSheet() và truyền tên file muốn tạo HSSFSheet sheet = workbook.createSheet("January");//tạo hàng thứ 0 sử dụng phương thức createRow() HSSFRow rowhead = sheet.createRow((short) 0);//tạo ô bằng cách sử dụng phương thức createCell() và thiết lập giá trị cho ô bằng cách sử dụng phương thức setCellValue() rowhead.createCell(0).setCellValue("S.No."); rowhead.createCell(1).setCellValue("Customer Name"); rowhead.createCell(2).setCellValue("Account Number"); rowhead.createCell(3).setCellValue("e-mail"); rowhead.createCell(4).setCellValue("Balance");//tạo hàng thứ 1 HSSFRow row = sheet.createRow((short) 1);//chèn dữ liệu vào hàng thứ 1 row.createCell(0).setCellValue("1"); row.createCell(1).setCellValue("John William"); row.createCell(2).setCellValue("9999999"); row.createCell(3).setCellValue(row.createCell(4).setCellValue("700000.00");//tạo hàng thứ 2 HSSFRow row1 = sheet.createRow((short) 2);//chèn dữ liệu vào hàng thứ 2 row1.createCell(0).setCellValue("2"); row1.createCell(1).setCellValue("Mathew Parker"); row1.createCell(2).setCellValue("22222222"); row1.createCell(3).setCellValue(row1.createCell(4).setCellValue("200000.00"); FileOutputStream fileOut = new FileOutputStream(filename); workbook.write(fileOut);//đóng stream fileOut.close();//đóng workbook workbook.close();//in thông báo tạo thành công System.out.println("File Excel đã được tạo thành công."); } catch (Exception e) { e.printStackTrace(); } } }[email protected]");[email protected]");

Kết quả:

“C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1jbrbinjava.exe” “-javaagent:C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1libidea_rt.jar=58597:C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2019.3.1bin” -Dfile.encoding=UTF-8 -classpath E:CoursesJavaCreateExcelFileoutproductionCreateExcelFile;E:CoursesJavaCreateExcelFilepoi-3.17.jar CreateExcelFileExample3 File Excel đã được tạo thành công.

Nó tạo một tệp excel tại vị trí được chỉ định với các giá trị mà ta đã chèn bằng cách sử dụng phương thức setCellValue().

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ách Link Dữ Liệu Từ File Excel Này Sang File Excel Khác

Chắc hẳn bạn đều biết Microsoft Excel là ứng dụng xử lý bảng tính nằm trong bộ MS Office của Microsoft, giúp người dùng trình bày các thông tin xử lý dưới dạng bảng dữ liệu, thực hiện việc tính toán, xây dựng các số liệu thống kê trực quan, hiệu quả. Ngoài những tính năng chính hay dùng thì việc sao chép, copy dữ liệu từ file Excel này sang file Excel khác cũng được thực hiện khá dễ dàng, qua đó giúp người dùng tìm kiếm, sắp xếp dữ liệu nhanh chóng, thuận tiện nhất.

Là một nhân viên bán hàng hay một quản lý, bạn chắc hẳn không xa lạ gì với Excel. Nó được coi là một trong những công cụ quản lý bán hàng, quản lý công nhân viên,…. vô cùng phổ biến.

Trong bài viết này, sẽ giới thiệu đến bạn cách di chuyển, copy sheet, link từ file Excel này sang file Excel khác sử dụng Excel 2016. Các phiên bản Excel khác như Excel 2013, 2010 các bạn thực hiện tương tự.

Để lấy dữ liệu từ file excel này sang file excel khác chúng ta cần thực hiện qua 7 bước sau đây:

Bước 1: Đầu tiên, bạn mở cả hai file Excel mà bạn cần xử lý lên. Ví dụ ở đây là File Excel 1 và File Excel 2

Bước 2: Mở nơi lưu file excel cần lấy dữ liệu ( ví dụ ở đây là file excel 1). Nhấp phải chuột vào file đó chọn properties.

Bước 3: Copy đường dẫn Location chọn OK

Bước 4: Dán đường dẫn vào file excel cần lấy dữ liệu

Bước 5: Thêm file excel chứa dữ liệu như bên dưới hình

Bước 6: Copy đường dẫn =’C:UsersAdminDesktop[thang3.xslx]Sheet1′!. Sau đó vào file excel chứa dữ liệu (cụ thể là file excel 2). Nhấp vào ô dữ liệu như bên dưới hình

Bước 7: Vào file excel cần lấy dữ liệu (file excel 1) và dán lại đường dẫn =’C:UsersAdminDesktop[thang3.xslx]Sheet1′! như bên dưới hình

Nhấn Enter để xem kết quả.

Tương tự, nếu bạn có những sheet khác mà cần chuyển sang file Excel khác thì bạn thực hiện tương tự như thao tác hướng dẫn trên. Nếu 2 sheet cùng tên (ví dụ sheet copy là sheet 1 và trong file Excel kia cũng có 1 sheet hiện hành là sheet 1) khi được copy sang thì nó sẽ hiển thị là Sheet1 (2).

Việc sao chép, chuyển sheet trong Excel ở trên, về cơ bản các thao tác để người dùng thực hiện khá đơn giản. Người dùng có thể di chuyển dữ liệu trong cùng một sheet hoặc có thể di chuyển hẳn sheet đó sang một file mới.

Theo Nhanh.vn

Đọc Ghi File Excel Trong Java Với Jxl

Tạo và ghi file Excel với Jxl

Bước 1: Tạo đối tượng WritableWorkbook “trỏ” đến file của bạn. Lưu ý là nếu file của bạn đã tồn tại thì nó sẽ bị xóa đi và tạo lại.

WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));

Bước 2: Tạo WritableSheet – sheet bạn cần ghi dữ liệu:

WritableSheet sheet = workbook.createSheet("name sheet", 0);

Lưu ý: trong hàm createSheet có 2 đối số, đối số thứ nhất là chuỗi tên sheet, đối số thứ 2 là một số nguyên chỉ vị trí của sheet, vị trí sheet bắt đầu bằng 0.

Bước 3: Tiếp theo chúng ta sẽ thêm các dạng dữ liệu vào các ô bằng phương thức addCell. Để viết dữ liệu vào các ô, chúng ta sẽ có 3 dạng chính: Chuỗi, Số và Công thức lần lượt được tạo bằng Label, Number, Formula. Ví dụ:

sheet.addCell(new Label(0, 0, "Add a String to cell")); sheet.addCell(new Number(0, 1, 100)); sheet.addCell(new Formula(0, 3, "IF(A1=1,"one", "two")"));

Bước 4: Sau khi chúng ta đã thực hiện xong bước 3, chúng ta cần thực hiện lệnh write và close để hoàn tất việc ghi dữ liệu

workbook.write(); workbook.close();

Đọc file Excel với Jxl

Bước 1: Tạo Workbook “trỏ” đến file của bạn.

Workbook workbook = Workbook.getWorkbook(new File(fileName));

Bước 2: Lấy Sheet bạn muốn đọc. Bạn có thể lấy theo vị trí sheet hoặc tên Sheet

Sheet sheet = workbook.getSheet(0);

Bước 3: Đọc nội dung từng ô trong bảng tính. Nếu bạn muốn lấy nội dung của một ô nào đó bạn có thể làm như sau: sheet.getCell(col, row).getContents(). Tuy nhiên nếu bạn muốn đọc toàn bộ các ô trong bảng tính hãy lấy hàng và cột cuối cùng chứa dữ liệu bằng sheet.getRows() và sheet.getColumns(), và dùng vòng lặp for để đọc từng ô. Sau khi đọc xong, chúng ta cũng cần close workbook như khi viết dữ liệu

for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { Cell cell = sheet.getCell(col, row); System.out.print(cell.getContents() + "t"); } System.out.println("n"); } workbook.close();

Mở và ghi thêm dữ liệu vào Excel với Jxl

Để mở và ghi thêm dữ liệu vào file Excel, trước tiên chúng ta cần lấy Workbook từ file Excel cần viết thêm giống như khi chúng ta đọc. Sau đó tạo một WritableWorkbook đến chính workbook vừa lấy và chúng ta sẽ làm việc với WritableWorkbook này bình thường.

Workbook workbook = Workbook.getWorkbook(new File(fileName)); WritableWorkbook writeWorkbook = Workbook.createWorkbook(new File(fileName), workbook);

Demo code

package vietSource.net.IOFile; import java.io.File; import java.io.IOException; import java.util.Scanner; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.Formula; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; /** */ public class ReadWriteExcel { private final String fileName = "/home/nguyenvanquan7826/Desktop/nguyenvanquan7826.xls"; private Object[][] data = { { "STT", "Họ và tên", "Điểm", "Xếp loại" }, { "1", "Nguyễn Văn Quân", "9.0", "" }, { "2", "Phạm Thị Hà", "8.0", "" }, { "3", "Nguyễn Bá Cường", "8.5", "" }, { "4", "Vũ Công Tịnh", "9.0", "" }, { "5", "Phạm Trọng Khang", "8", "" }, { "6", "Mai Văn Tài", "8", "" } }; private void writeFileExcel() { WritableWorkbook workbook; try { workbook = Workbook.createWorkbook(new File(fileName)); WritableSheet sheet1 = workbook.createSheet("KTPM K10B", 0); sheet1.addCell(new Label(0, 0, "DANH SÁCH SINH VIÊN TIÊU BIỂU")); int rowBegin = 2; int colBegin = 0; for (int row = rowBegin, i = 0; row < data.length + rowBegin; row++, i++) { for (int col = colBegin, j = 0; col < data[0].length + colBegin; col++, j++) { Object obj = data[i][j]; sheet1.addCell(new Label(col, row, (String) data[i][j])); } } workbook.write(); workbook.close(); } catch (IOException e) { System.out.println("Error create file " + e.toString()); } catch (RowsExceededException e) { System.out.println("Error write file " + e.toString()); } catch (WriteException e) { System.out.println("Error write file " + e.toString()); } System.out.println("create and write success"); } private void readFileExcel() { Workbook workbook; try { workbook = Workbook.getWorkbook(new File(fileName)); Sheet sheet = workbook.getSheet(0); int rows = sheet.getRows(); int cols = sheet.getColumns(); System.out.println("Data in file:"); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { Cell cell = sheet.getCell(col, row); System.out.print(cell.getContents() + " "); } System.out.println(" "); } workbook.close(); } catch (BiffException e) { System.out.println("File not found " + e.toString()); } catch (IOException e) { System.out.println("File not found " + e.toString()); } } private void openAndWriteFileExcel() { Workbook workbook; WritableWorkbook writeWorkbook; try { workbook = Workbook.getWorkbook(new File(fileName)); writeWorkbook = Workbook.createWorkbook(new File(fileName), workbook); WritableSheet sheet1 = writeWorkbook.getSheet(0); int col = 3; int rowBegin = 3; for (int row = rowBegin; row < data.length + rowBegin - 1; row++) { Formula f = new Formula(col, row, "IF(C" + (row + 1) sheet1.addCell(f); } writeWorkbook.write(); writeWorkbook.close(); } catch (IOException e) { System.out.println("File not found " + e.toString()); } catch (RowsExceededException e) { System.out.println("File not found " + e.toString()); } catch (WriteException e) { System.out.println("File not found " + e.toString()); } catch (BiffException e) { System.out.println("File not found " + e.toString()); } System.out.println("open and write success"); } private void showMenu() { System.out.println(); System.out.println("Select an integer for process:"); System.out.println("1 - Create new file and wrire data"); System.out.println("2 - Read file exits"); System.out.println("3 - Open and write to file exits"); } public static void main(String[] args) { ReadWriteExcel rwExcel = new ReadWriteExcel(); while (true) { rwExcel.showMenu(); Scanner scan = new Scanner(System.in); int select = Integer.parseInt(scan.nextLine()); switch (select) { case 1: rwExcel.writeFileExcel(); break; case 2: rwExcel.readFileExcel(); break; case 3: rwExcel.openAndWriteFileExcel(); break; default: scan.close(); break; } } } }