[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
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
For emhoi read using Excel functions. When you retrieve the data, the data error status Vietnamese font
example: Le Dung => Le D?of
Can you help me how to solve not !:D
His reading was delicious :D, Posts are also tasty.
Search through, they said this set. You try not to view, if you can not use another library but is too difficult to use than And then
try to install the font with JXL:
Thanks you! em làm được rồi 😀
Do you use or how you make this way?
cái đoạn code này thêm ở đâu vậy ad??
Đây chỉ là code đọc ghi thôi, bạn ứng dụng vào đâu thì tùy bạn nhé.
He asked me to read excel then use the Galaxy range market, the Galaxy did not read but it fails again “h” The average word error also like this “Mid bnh”
You try to install fonts in this view offline
https://www.cachhoc.net/2014/06/20/java-doc-ghi-file-excel-trong-java-voi-jxl-read-write-excel-file-in-java-with-jxl/#comment-1439
Dear anh Quân.
Anh Quâ cho em hỏi vì sao máy em không import được jxl.write.Label, mặc dù các cái khác thì import được, em kiểm tra trong library cũng đã có Label.class rồi ?
The thing they do not know. Bạn viết thẳng ra xem đk ko
He asked me, em muốn hiện file Excel trên giao diện thì làm như thế nào ạ. Such for tex file, use JTextArea, Excel also, I do not know. He just helped me with. Thank you sir.
The thing I also have never tried it you ah.
He found out that he asked me to know with sir, they are to be handled this issue urgently, could not ask anyone. I thank you very much.
If you read the data inside of launching cell, they may put data on o king crab read JTable
Yeah you
Hello! you have problems like this article:Write a program that has the function of supporting the online document editor as a spreadsheet(giống google sheet). I can show you need to learn about the problem to be able to do, by java. thank you
This is a bit difficult, but you can learn table in java.
table in java, I know it, but the problem here is how to manage the boxes on the table where many people can operate simultaneously on the table. For a few seconds that I have about logging work.
then every time it updates its logging or otherwise when they save or reload, then we load the changes of everyone. But to ensure the actions of each of them saved.
Kids to organize stored in log files such as database management system so. but retrieving it would be difficult to check the log file for the cilent can work on multiple cells. better is to hold up the log directly into the excel file. then want to check only the call-up. Anyway, thanks a given comments
I think that should be saved in files.
I've held up under the file but trouble in space is how to later 5 there are 10 second, it automatically saves down. so do it your way e is about 5 -10s is currently caught notify users save, this will cause inconvenience . he has a way to solve e
Maybe yes 1 background process to save. Read more about Thread nhé
they did it! thanks a
to
If I write times 3,4 ,5… how about you. When file already exists .
Then we have said above and that. The opening and put you.
Auntie, here's how to ask for e export excel files with data entered manually, if the data after running the program from console themselves that they want to export to excel sir ntn?
Then run the console, Import saved to then write normal variable
Hi Army,
Asked declared themselves in Java How to Set is the width of each column in Excel when writing is fit to the data.
Thanks,
Can Nguyen
I also do not understand this, try google you see, if you wish to update the way here for people offline.
can manipulate excel file excel file but in the phenotype, it can manipulate like strings are not so A ?