Operate Excel files -- java; Operate excel -- java
To operate Excel in java, you must first import JExcelAPI
JExcelAPI is a set of Excel sheet operation components developed purely using JAVA. It is not bound to a specific operating system and can operate Excel files on different operating systems, JXL is: http://www.andykhan.com/jexcelapi/. this document uses jexcelapi_2_6_12.tar.gz.
The jdk and JXL versions may be used. The current version is JDK1.6.
You only need to import the JXL. jar file in the JExcelAPI Development Kit, the most important of which are the following classes:
Workbook: a complete Excel File
WritableWorkbook: defines a blank Excel file to be output, but to obtain this object, you need to use the createWorkbook () method of the Workbook class to complete
WritableSheet: indicates the Sheet of each Excell.
Cell: Indicates each specific Cell.
The code for creating an Excel file is as follows:
Import java. io. file; import jxl. workbook; import jxl. write. label; import jxl. write. writableSheet; import jxl. write. writableWorkbook; public class CreateSimpleExcel {public static void main (String [] args) throws Exception {String data [] [] ={{ "my ", "oumyye ", "20" },{ "oumyye", "oumyye", "www.oumyye.com" }}; // information to be output File outFile = new File ("D:" + File. separator + "oumyye.xls"); WritableWorkbook workbook = Workbook. createWorkbook (outFile); WritableSheet sheet = workbook. createSheet ("oumyye", 0); Label lab = null; for (int x = 0; x <data. length; x ++) {for (int y = 0; y <data [x]. length; y ++) {lab = new Label (y, x, data [x] [y]); sheet. addCell (lab) ;}} workbook. write (); workbook. close ();}}You can also read information from xls:
import java.io.File;import jxl.Sheet;import jxl.Workbook;public class LoadExcel { public static void main(String[] args) throws Exception { File inFile = new File("D:" + File.separator + "oumyye.xls"); Workbook workbook = Workbook.getWorkbook(inFile); Sheet sheet[] = workbook.getSheets(); for (int x = 0; x < sheet.length; x++) { for (int y = 0; y < sheet[x].getRows(); y++) { for (int z = 0; z < sheet[x].getColumns(); z++) { String content = sheet[x].getCell(z, y).getContents(); System.out.print(content + "\t\t") ; } System.out.println() ; } } }}
Running result:
After processing the data in an Excel worksheet, you must use the close () method to close the previously created object to release the memory space occupied by reading the data table, it is particularly important to read a large amount of data.