Java——jxl操作Excel
需要利用的jar包:jxl-2.6.12.jar
http://pan.baidu.com/s/1o7KtxUi
1、读取xls文件
package test;
import java.io.File;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ReadExcel {
// 写入excel
public static void main(String[] args) {
try {
Workbook book = Workbook.getWorkbook(new File("d:\\测试.xls"));
// 获得第一个sheet对象
Sheet sheet0 = book.getSheet(0);
// 获取总行、列数
int rows = sheet0.getRows();
int cols = sheet0.getColumns();
System.out.println("行:" + rows);
System.out.println("列:" + cols);
// 循环读取数据
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(sheet0.getCell(j, i).getContents()+" ");
}
System.out.println();
}
} catch (BiffException | IOException e) {
e.printStackTrace();
}
}
}
2、写入xls文件
package test;
import java.io.File;
import java.io.IOException;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class WriteExcel {
//写入excel
public static void main(String[] args) {
try {
// 创建jxl操作对象
WritableWorkbook book = Workbook.createWorkbook(new File("d:\\测试.xls"));
// 创建sheet(name、num)
WritableSheet sheet0 = book.createSheet("sheet0", 0);
// 创建表格(row、col、value)
//行
for (int i = 0; i < 10; i++) {
//列
for (int j = 0; j < 10; j++) {
Label label = new Label(j, i, "第"+(i+1)+"行");
// 将表格添加到sheet
sheet0.addCell(label);
}
}
// 写入数据
book.write();
// 关闭流
book.close();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
3、修改xls文件
package test;
import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ModifyExcel {
public static void main(String[] args) {
try {
// 获取excel文件
Workbook wb = Workbook.getWorkbook(new File("d:\\测试.xls"));
// 生成副本
WritableWorkbook book = Workbook.createWorkbook(new File("d:\\测试.xls"), wb);
// 例如——添加一个工作表
WritableSheet sheet1 = book.createSheet("sheet1", 1);
// 创建表格
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 10; j++) {
Label label = new Label(j, i, "第" + i + "行");
//添加表格到sheet
sheet1.addCell(label);
}
}
// 写入
book.write();
// 关闭流
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}