使用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;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFRichTextString;
importorg.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
importorg.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(newHSSFRichTextString(names[j]));
}
for (int i = 0; i < xls.size(); i++) {
// 创建一行
HSSFRow row = sheet.createRow(i +1);
// 得到要插入的每一条记录
content = xls.get(i);
for (int colu = 0; colu <= 4;colu++) {
// 在一行内循环
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();
}
publicstatic void main(String[] args) throws Exception{
//初始化数据,内部类的构造有点特殊
List<Content>contents = new ArrayList<Content>();
contents.add(newEasyExcel().new Content("100","name100"));
contents.add(newEasyExcel().new Content("101","name101"));
contents.add(newEasyExcel().new Content("102","name102"));
longstart = System.currentTimeMillis();
EasyExcelexcel = new EasyExcel();
excel.createExcelFile("d:/ffm83/easyExcel.xls",contents);
longend = System.currentTimeMillis();
System.out.println("生成excel文件耗时:"+ (end - start) + "(毫秒)");
}
//一个简单的保存简单信息的内部类
publicclass Content {
privateString code;
private String name;
public Content(String code,String name){
this.code= code;
this.name= name;
}
publicString getCode() {
returncode;
}
publicvoid setCode(String code) {
this.code= code;
}
publicString getName() {
returnname;
}
publicvoid setName(String name) {
this.name= name;
}
}
}