[Java] Read the Excel file in Java with JXL – Read write Excel file in Java with jxl

In the course of work and data processing we often have to interact with the file especially Excel File. Today I'll show you the simple steps to read Excel files recorded with JXL. JXL is a library package allows us to interact called Excel as read, record,.., Detailed information about the package you see JXL here.

First of all you download Jxl (or here), unzip the * .jar file then copy just in project, right click select Build Path / Add to Build Path to be able to use this library. Now we turn to learn:
How to create and write Excel files with JXL
How to read Excel file with JXL
How to open and write to Excel files had to JXL
Code illustrations

Create and write Excel files with JXL

Step 1: Create objects WritableWorkbook “point” to file your. Note that if your file already exists, it will be deleted and recreated.

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

Step 2: Create WritableSheet – you need to write data sheet:

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

Noted: in function can createSheet 2 argument, The first argument is the string name of sheet, the second argument 2 is an integer representing the position of the sheet, sheet position begins with 0.

Step 3: Next we will add the data format to cells by methods addCell. To write data into the cell, we will have 3 The main form: Chain, Number and Formula respectively generated by Label, Number, Formula. Example:

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

Step 4: After we have done this 3, we need to execute the command write and close to complete the data record

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

Read Excel file with JXL

Step 1: Create Workbook “point” to file your.

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

Step 2: Taken Sheet You want to read. You can get the location or name sheet Sheet

Sheet sheet = workbook.getSheet(0);

Step 3: Read the contents of each cell in the spreadsheet. If you want to get the contents of a box that you can do the following: sheet.getCell(with, row).getContents(). But if you want to read the entire cell in the worksheet take the last row and column containing the data by sheet.getRows() and sheet.getColumns(), and use a for loop to read each cell. After reading, we also need close workbook when writing 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();

Open and put the data into Excel with JXL

To open and put the data into Excel file, First we need to get Workbook from the Excel file should write more like when we read. Then create a WritableWorkbook to the workbook has taken and we will work with this WritableWorkbook normal.

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.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;

/**
 * ----------------- @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];
					sheet1.addCell(new Label(col, row, (String) 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;
			}
		}
	}
}

Read more (read more): Java Excel API Tutorial