读写Excel的常用三种技术
- POI(Apache)
- JXL
- FASTEXCEL
用JXL生成excel
- 导包:由于我是用maven的,所以我就到pom加入:
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
- java代码:
public static void main(String[] args){
//设置表头
String[] title = {"id","name","sex"};
//创建excel文件
File file = new File("d:/jxl_text.xls");
try {
file.createNewFile();
//创建工作簿
WritableWorkbook workBook = Workbook.createWorkbook(file);
WritableSheet sheet = workBook.createSheet("Sheet1",0);
Label label = null;
//第一行设置列名,第一行的时候for循环中的i要为0
for (int i = 0;i<title.length;i++){
label = new Label(i,0,title[i]);//第几列:i,第几行:0,值:title[i]
sheet.addCell(label);
}
//追加数据
for (int i = 1;i<10;i++){
label = new Label(0,i,"a"+1);//第几列:0,第几行:i,值:a1
sheet.addCell(label);
label = new Label(1,i,"user"+1);//第几列:1,第几行:i,值:user1
sheet.addCell(label);
label = new Label(2,i,"男");//第几列:2,第几行:i,值:男
sheet.addCell(label);
}
//写入数据
workBook.write();
//关闭流
workBook.close();
} catch (IOException e) {
e.printStackTrace();
}catch (WriteException e){
e.printStackTrace();
}
}