助于jxl.jar,由于不支持上传文件,所以请自行百度下载jxl.jar,在应用程序中添加jxl.jar包,并将需要读取的excel文件放入根目录即可。
本例使用java来读写excel的内容,代码如下:
import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class JxlExpExcel {
private static final File file = new File("jxl_test.xls");
/**
* 导出Excel
*/
private static void exportExcel() {
String[] title = {"id","name","sex"};
//创建Excel文件
try {
if(!file.exists())
file.createNewFile();
//创建工作簿
WritableWorkbook workbook = Workbook.createWorkbook(file);
//创建sheet
WritableSheet sheet = workbook.createSheet("信息表", 0);
workbook.createSheet("信息表2", 1);
Label label = null;
//第一行设置列名
for(int i = 0;i < title.length; i++) {
label = new Label(i, 0, title[i]);
sheet.addCell(label);
}
//追加数据
//第一个参数是列,从0开始;第二个参数是行,去除标题后从1开始;第三个参数是内容;
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();
}
}
/**
* 导入Excel
*/
public static void importExcel() {
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook(file);
Sheet sheet = workbook.getSheet("信息表"); //或者sheet.getSheet(0)
//总列数
int cols = sheet.getColumns();
//总行数
int rows = sheet.getRows();
//列从0开始,行去除标题后从1开始
for(int row = 1; row < rows; ++row) {
int col = 0;
String id = sheet.getCell(col++, row).getContents();
String name = sheet.getCell(col++, row).getContents();
String sex = sheet.getCell(col++, row).getContents();
System.out.println("id:" + id + " name:" + name + " sex:" + sex);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭workbook
workbook.close();
}
}
public static void main(String[] args) {
//导出
exportExcel();
//导入
importExcel();
}
}
展示打印结果:
id:a1 name:user1 sex:男
id:a2 name:user2 sex:男
id:a3 name:user3 sex:男
id:a4 name:user4 sex:男
id:a5 name:user5 sex:男
id:a6 name:user6 sex:男
id:a7 name:user7 sex:男
id:a8 name:user8 sex:男
id:a9 name:user9 sex:男