jxl是一个韩国人写的java操作excel的工具, 在开源世界中,有两套比较有影响的API可 供使用,一个是POI,一个是jExcelAPI。其中功能相对POI比较弱一点。但jExcelAPI对中文支持非常好,API是纯Java的, 并不 依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。 另外需要说明的是,这套API对图形和图表的支持很有限,而且 仅仅识别PNG格式。
1、创建一个test.xls文件,向其写入数据
2、从test.xls文件中读出数据
- package com.ccit;
- import jxl.Workbook;
- import jxl.write.Label;
- import jxl.write.WritableSheet;
- import jxl.write.WritableWorkbook;
- import java.io.File;
- /**
- * Created by dong on 15-4-18.
- */
- public class JxlExpExcel {
- public static void main(String[] args) {
- String[] title = {"id","name","sex"};
- //创建Excel文件
- File file = new File("src/doc/test.xls");
- try {
- file.createNewFile();
- //创建工作簿
- WritableWorkbook workbook = Workbook.createWorkbook(file);
- //创建sheet页
- WritableSheet sheet =workbook.createSheet("sheet",0);
- Label label = null;
- //第一行设置列名
- for(int i=0; i<title.length;i++){
- label = new Label(i,0,title[i]);
- sheet.addCell(label);
- }
- //网excel中加入数据
- for(int i=1;i<10;i++){
- label = new Label(0,i,"a"+i);
- sheet.addCell(label);
- label = new Label(1,i,"user"+i);
- sheet.addCell(label);
- label = new Label(2,i,"男");
- sheet.addCell(label);
- }
- //写入数据
- workbook.write();
- workbook.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- package com.ccit;
- import jxl.Cell;
- import jxl.Sheet;
- import jxl.Workbook;
- import java.io.File;
- /**
- * Created by dong on 15-4-18.
- */
- public class JxlReadExcel {
- public static void main(String[] args) {
- try {
- //创建workbook
- Workbook workbook =Workbook.getWorkbook(new File("src/doc/test.xls"));
- //获取sheet
- Sheet sheet =workbook.getSheet(0);
- //获取数据
- for(int i=0;i<sheet.getRows();i++){
- for(int j=0;j<sheet.getColumns();j++){
- Cell cell =sheet.getCell(j,i);
- System.out.print(cell.getContents()+" ");
- }
- System.out.println();
- }
- workbook.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
来源: http://www.phpxs.com/code/1002039/