Java EXCEL and java excel
Today, I wrote a program for my friends to process the EXCEL content. Here I will record my learning process. It is mainly used to classify and collect statistics on the content in an EXCEL table, so it is better to use a computer to do such repetitive mechanical work. First, we need to download an open-source plug-in for java excel operations. I am using jexcelapi (download link: http: // 120.52.73.49/nchc.dl.sourceforge.net/project/jexcelapi/jexcelapi/2.6.6/jexcelapi_2_6_6.zip ). Decompress the package. If you use Eclipse or other IDE, you must add the jxl. jar file in project> properties> Java Build Path. Now, the development environment has been set up. Perform the following operations:
1. Define the data type. Because the data types of each column are different, the class data type is used for storage, and the object array is used to store the content of each row.
Class record {private int num; private char ty; public void SetNum (String s1) {this. num = Integer. parseInt (s1);} public void SetTy (String s2) {this. ty = (char) s2.getBytes () [0];} public int GetNum () {return num;} public char GetTy () {return ty ;}} record a [] = new record [row]; for (int I = 0; I <row; I ++) a [I] = new record ();View Code
Pay attention to the initialization process of each element in the object array in the Code. Otherwise, an exception of java. lang. NullPointerException will occur.
2. Connect to EXCEL to get the workspace. We use the Workbook and Sheet classes in the jxl package we imported earlier.
// Create a Workbook book = Workbook container for reading excel. getWorkbook (new File ("G:/test123.xls"); // read the first page of Sheet sheet = book. getSheet (0); // read the workbook, the number of columns, and the number of rows int col = sheet. getColumns (); int row = sheet. getRows ();View Code
3. Read the content of each cell. After reading the cell data to the array, you can perform the following operations based on the actual situation.
For (int I = 0; I <row; I ++) {// The first parameter represents the column, and the second parameter represents the row Cell cell1 = sheet. getCell (0, I); Cell cell2 = sheet. getCell (1, I); a [I]. set_num (cell1.getContents (); a [I]. set_ty (cell2.getContents ());}View Code
4. After completing the related operations as needed, you need to write the data to the Excel table. We use WritableWorkbook and WritableSheet classes.
// Create an excel file WritableWorkbook bookw = Workbook. createWorkbook (new File ("G:/testwtb.xls"); // write to the first page of excel writablesheetw = bookw. createSheet ("first sheet", 0); for (int I = 0; I <= index; I ++) {Number n = new Number (0, I, x [I]); sheetw. addCell (n); Number n1 = new Number (1, I, y [I]); sheetw. addCell (n1); Number n2 = new Number (2, I, z [I]); sheetw. addCell (n2); Number n3 = new Number (3, I, xx [I]); sheetw. addCell (n3);} bookw. write (); bookw. close ();View Code
So far, all operations have been completed.