使用poi生成EXCEL
在很多的场合,需要使用EXCEL文件。一般是表格方面的应用,简单的示例。
需要引入第三方jar包:poi_3.6.jar
package com.daily;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* 生成EXCEL
* @author 范芳铭
*/
public class EasyExcel {
public void createExcelFile(String outFilename,List<Content> xls) throws Exception {
// 获取总记录条数
int CountColumnNum = xls.size();
// 创建Excel文档
HSSFWorkbook hwb = new HSSFWorkbook();
Content content = null;
// sheet 对应一个工作页
HSSFSheet sheet = hwb.createSheet("ffm");
HSSFRow firstrow = sheet.createRow(0); // 下标为0的行开始
HSSFCell[] firstcell = new HSSFCell[CountColumnNum];
String[] names = new String[CountColumnNum];
names[0] = "编码";
names[1] = "姓名";
for (int j = 0; j < CountColumnNum; j++) {
firstcell[j] = firstrow.createCell(j);
firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
}
for (int i = 0; i < xls.size(); i++) {
// 创建一行
HSSFRow row = sheet.createRow(i + 1);
// 得到要插入的每一条记录
content = xls.get(i);
// 在一行内循环 ,根据需要的属性设置
HSSFCell one = row.createCell(0);
one.setCellValue(content.getCode());
HSSFCell two = row.createCell(1);
two.setCellValue(content.getName());
}
// 创建文件输出流,准备输出电子表格
OutputStream out = new FileOutputStream(new File(outFilename));
hwb.write(out);
out.close();
}
public static void main(String[] args) throws Exception{
//初始化数据,内部类的构造有点特殊
List<Content> contents = new ArrayList<Content>();
contents.add(new EasyExcel().new Content("100","name100"));
contents.add(new EasyExcel().new Content("101","name101"));
contents.add(new EasyExcel().new Content("102","name102"));
long start = System.currentTimeMillis();
EasyExcel excel = new EasyExcel();
excel.createExcelFile("d:/ffm83/easyExcel.xls",contents);
long end = System.currentTimeMillis();
System.out.println("生成excel文件耗时:" + (end - start) + "(毫秒)");
}
//一个简单的保存简单信息的内部类
public class Content {
private String code;
private String name;
public Content(String code,String name){
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
运行结果:
生成excel文件耗时:149(毫秒)