利用poi输出Excel文件是java应用导出excel文件最常用的方法,下面我做了一个简单的应用例子,包括单个sheet的excel文件和多个sheet的excel文件生成。
1, 首先第一步需要导入下载的java包,据我实际测试,需要加入如下几个jar包到类路径下即可:jxl.jar,jxls-core-0.9.1.jar,poi-2.5.1-final-20040804.jar, poi-contrib-2.5.1-final-20040804.jar, poi-scratchpad-2.5.1-final-20040804.jar, commons-logging-1.1.jar, commons-jexl-1.1.jar.,如图所示
2, 做实体对象类: OdEntity
public class OdEntity {
private String pmId;
private String pmName;
public String getPmId() {
return pmId;
}
public void setPmId(String pmId) {
this.pmId = pmId;
}
public String getPmName() {
return pmName;
}
public void setPmName(String pmName) {
this.pmName = pmName;
}
}
3, 做模板文件export_template.xls,如图所示
4, 实现代码:
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import axisoft.entity.OdEntity;
import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;
public class TestExport {
/**
* @param args
*/
public static void main(String[] args) {
//TestExport.multiSheet();
TestExport.singleSheet();
}
/**
* single-Sheet
*
*/
public static void singleSheet(){
XLSTransformer transformer = new XLSTransformer();
String xlsTemplateFileName = "export_template.xls";
String xlsFileName = "output.xls";
Map<String, ArrayList<OdEntity>> beans = new HashMap<String, ArrayList<OdEntity>>();
ArrayList<OdEntity> list = new ArrayList();
OdEntity ent=new OdEntity();
ent.setPmId("aaaaa");
ent.setPmName("AAAAA");
list.add(ent);
OdEntity ent1=new OdEntity();
ent1.setPmId("bbbbb");
ent1.setPmName("BBBBB");
list.add(ent1);
beans.put("od",list);
try {
transformer.transformXLS(xlsTemplateFileName , beans, xlsFileName);
} catch (ParsePropertyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* multi-Sheets
*
*/
public static void multiSheet(){
XLSTransformer transformer = new XLSTransformer();
String xlsTemplateFileName = "export_template.xls";
String xlsFileName = "output.xls";
ArrayList<ArrayList<OdEntity>> obj = new ArrayList();
ArrayList<OdEntity> list = new ArrayList();
OdEntity ent=new OdEntity();
ent.setPmId("aaaaa");
ent.setPmName("AAAAA");
list.add(ent);
OdEntity ent1=new OdEntity();
ent1.setPmId("bbbbb");
ent1.setPmName("BBBBB");
list.add(ent1);
obj.add(list);
OdEntity ent2=new OdEntity();
ArrayList<OdEntity> list1 = new ArrayList();
ent2.setPmId("ccccc");
ent2.setPmName("CCCCC");
list1.add(ent2);
OdEntity ent3=new OdEntity();
ent3.setPmId("ddddd");
ent3.setPmName("DDDDD");
list1.add(ent3);
obj.add(list1);
ArrayList<String> nameList = new ArrayList();
nameList.add("A-B");
nameList.add("C-D");
try {
InputStream xlsTemplateIO = new FileInputStream(xlsTem