关于使用java的操作excel的方法有很多种,我的http://blog.csdn.net/qq_20545159/article/details/45132041价绍过,下面是使用jxl生成xls格式的excel简单的代码。
使用jxl生成excel文件首先必须将jxl.jar的包加到你的项目的路径下。
package com.silence.excel;import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class jxlExcel {
public static void main(String[] args) {
// 设置该表格的行标签
String[] title = { "id", "name", "age", "sex", "number" };
// 创建文件
File file = new File("e:\\temp.xls");
try {
if (!file.exists()) {
file.createNewFile();
}
// 创建工作普
WritableWorkbook workbook = Workbook.createWorkbook(file);
// 创建sheet
WritableSheet sheet = workbook.createSheet("sheet0", 0);
Label label = null;
// 设置一行列名
for (int i = 0; i < title.length; i++) {
label = new Label(i, 0, title[i]);
sheet.addCell(label);
}
// 循环向每一行中插入数据
for (int i = 0; i < 10; i++) {
label = new Label(0, i, "user" + i);
sheet.addCell(label);
label = new Label(1, i, "张三" + i);
sheet.addCell(label);
label = new Label(2, i, 21 +i+"");
sheet.addCell(label);
label = new Label(3, i, "a" + i);
sheet.addCell(label);
label = new Label(4, i, "silencewaking in the sun " + i);
sheet.addCell(label);
}
//结束
workbook.write();workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
java读取excel
package com.silence.excel;
import java.io.File;
import java.io.IOException;import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class jxlReadExcel {
public static void main(String[] args) {
try {
//创建workbook
Workbook workbook = Workbook.getWorkbook(new File("e:\\temp.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 (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}