Trong quá trinh làm việc và xử lý dữ liệu chúng ta thường phải tương tác với các file đặc biệt là File Excel. Hôm nay mình sẽ hướng dẫn các bạn các bước đơn giản để đọc ghi file Excel với jxl. Jxl là một gói thư viện cho phép chúng ta tương tác gới Excel như đọc, ghi,.., về thông tin chi tiết gói jxl các bạn xem tại đây.

Trước tiên các bạn download Jxl (hoặc tại đây), giải nén sau đó copy file *.jar vừa vào project, ấn chuột phải chọn Build Path / Add to Build Path để có thể sử dụng thư viện này. Bây giờ chúng ta lần lượt tìm hiểu:
Cách tạo và ghi file Excel với Jxl
Cách đọc file Excel với Jxl
Cách mở và ghi tiếp file Excel đã có với Jxl
Code minh họa

When we processing data, we often have work with Excel file. To day, I will tutorial you step by step to read and write Excel file with Jxl. Jxl is package allow we work with Excel file as read, write, …, you can read more infomation here.

The frist, you download Jxl (or here), extract and then copy file *.jar into project, right click, select Build Path / Add to Build Path to add library. Now we will find out:
Create and write file Excel with Jxl
Read Excel file with Jxl
Open and Write more Excel with Jxl
Demo code

Tạo và ghi file Excel với Jxl – Create and write file Excel with 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.

Step 1: Create a WritableWorkbook reference to your file. Note, if your file is exist, it will be delete and create new file.

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

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

Step 2: Create a WritableSheet – sheet you want write data, e.g:

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ụ:

Note: in function createSheet have two parameter, first is a String, it is name sheet, the second is a integer number, it is position of sheet. the first sheet being 0, the second sheet being 1, and so on.

Step 3: Now, We will add data by method strong>addCell. We have three type of data, they are: String, Number and Furmula. We create them by Label, Number, Formula. eg:

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

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 writeclose để hoàn tất việc ghi dữ liệu

Step 4: After we finish step 3, we must execute write and close to finish write data.

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

Đọc file Excel với Jxl – Read Excel file with Jxl

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

Step 1: Create a Workbook reference to your file

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

Step 2: Get a Sheet you want read. You can get sheet by index or sheet name.

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()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

Step 3: Read content each cell. If you want get content of a cell, you can sheet.getCell(col, row).getContents(). But, if you want read all cell in workbook, you must get last column and row contain data by sheet.getRows() and sheet.getColumns() and then use loop for to read each cell. The last, we must close workbook same write data.

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 – Open and Write more Excel with 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.

To accomplish, we get Workbook from Excel file want write same read Excel. Then, we create a WritableWorkbook reference to Workbook and we will work with WritableWorkbook.

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

Demo code

read wirte Excel file in java

package vietSource.net.IOFile;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.StringFormulaCell;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

/**
 * ----------------- @author nguyenvanquan7826 -----------------
 * ---------------nguyenvanquan7826.wordpress.com --------------
 */
public class ReadWriteExcel {

	private final String fileName = "/home/nguyenvanquan7826/Desktop/nguyenvanquan7826.xls";

	// data to write file
	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, "" } };

	// create and write new file *.xls
	private void writeFileExcel() {
		WritableWorkbook workbook;
		// create workbook
		try {
			workbook = Workbook.createWorkbook(new File(fileName));

			// create sheet
			WritableSheet sheet1 = workbook.createSheet("KTPM K10B", 0);

			// create Label and add to sheet
			sheet1.addCell(new Label(0, 0, "DANH SÁCH SINH VIÊN TIÊU BIỂU"));

			// row begin write data
			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];
					// write a string to cell
					if (obj instanceof String)
						sheet1.addCell(new Label(col, row, (String) data[i][j]));
					// write a integer number to cell
					else if (obj instanceof Integer)
						sheet1.addCell(new Number(col, row,
								(Integer) data[i][j]));
					// write a double number to cell
					else if (obj instanceof Double)
						sheet1.addCell(new Number(col, row, (Double) data[i][j]));
				}
			}
			// write file
			workbook.write();

			// close
			workbook.close();
		} catch (IOException e) {
			System.out.println("Error create file\n" + e.toString());
		} catch (RowsExceededException e) {
			System.out.println("Error write file\n" + e.toString());
		} catch (WriteException e) {
			System.out.println("Error write file\n" + e.toString());
		}
		System.out.println("create and write success");
	}

	// open and read file *.xls
	private void readFileExcel() {
		Workbook workbook;
		try {
			// create workbook to open file
			workbook = Workbook.getWorkbook(new File(fileName));
			// get sheet want read
			Sheet sheet = workbook.getSheet(0);
			// get number row and col contain data
			int rows = sheet.getRows();
			int cols = sheet.getColumns();

			System.out.println("Data in file:");
			// read data in each cell
			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");
			}
			// close
			workbook.close();
		} catch (BiffException e) {
			System.out.println("File not found\n" + e.toString());
		} catch (IOException e) {
			System.out.println("File not found\n" + e.toString());
		}
	}

	// open and write file is exists
	private void openAndWriteFileExcel() {
		Workbook workbook;
		WritableWorkbook writeWorkbook;
		try {
			// open file
			workbook = Workbook.getWorkbook(new File(fileName));
			// create file copy of root file to write file
			writeWorkbook = Workbook.createWorkbook(new File(fileName),
					workbook);

			// get sheet to write
			WritableSheet sheet1 = writeWorkbook.getSheet(0);
			int col = 3;
			int rowBegin = 3;
			// write data (formula)
			for (int row = rowBegin; row < data.length + rowBegin - 1; row++) {
				Formula f = new Formula(col, row, "IF(C" + (row + 1)
						+ ">8, \"Xuất sắc\", \"Giỏi\")");
				sheet1.addCell(f);
			}
			writeWorkbook.write();

			// close
			writeWorkbook.close();
		} catch (IOException e) {
			System.out.println("File not found\n" + e.toString());
		} catch (RowsExceededException e) {
			System.out.println("File not found\n" + e.toString());
		} catch (WriteException e) {
			System.out.println("File not found\n" + e.toString());
		} catch (BiffException e) {
			System.out.println("File not found\n" + 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;
			}
		}
	}
}

Đọc thêm (read more): Java Excel API Tutorial