利用jxl创建excel文件
所需jar包 jxl.jar
public class JxlExpExcel {
/*
* 使用jxl生成excel
*/
public static void main(String[] args) {
String[] title = {"id","name","sex"};
//创建Excel文件
File file = new File("e:/jxl_test.xls");
try {
file.createNewFile();
//创建工作簿
WritableWorkbook workbook = Workbook.createWorkbook(file);
//创建sheet
WritableSheet sheet = workbook.createSheet("sheet1", 0);
Label label = null;
//往sheet里写入数据
//第一行设置列名
for (int i = 0; i < title.length; i++) {
label = new Label(i,0,title[i]);
sheet.addCell(label);
}
//追加数据
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();
}
}
}
2,读取excel里的数据打印到控制台
public class JxlReadExcel {
/**
*jxl读取excel内容
*/
public static void main(String[] args) {
try {
//新建workbook
Workbook workbook = Workbook.getWorkbook(new File("e:/jxl_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();
}
}
}
转载于:https://blog.51cto.com/hatch/1669813