1.Apache POI简介
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 POI 的功能。
2.POI结构
HSSF - 提供读写Microsoft Excel XLS格式档案的功能。
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
HWPF - 提供读写Microsoft Word DOC格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读Microsoft Visio格式档案的功能。
HPBF - 提供读Microsoft Publisher格式档案的功能。
HSMF - 提供读Microsoft Outlook格式档案的功能。
3.POI实现
/**
* 导出辅助类
* @author Administrator
*
*/
public class exportExcle {
/**
* 导出Excel
* @param dataList 要导出的list
* @param response
* @param mapTitle excel标题头
* @param strEntityName 对应的实体
* @param strSheetName sheet名称
* @param strFileName excel名字
* @param assistMap 辅助传值
* @throws Exception
*/
@SuppressWarnings({ "unused", "rawtypes" })
public static void exportExcleMethod(List dataList, HttpServletResponse response,Map mapTitle,String strEntityName,String strSheetName,String strFileName ,Map assistMap) throws Exception {
OutputStream ou = response.getOutputStream();
Workbook wb = new HSSFWorkbook();
OutputStream out = new FileOutputStream(strFileName);
Sheet sheet = wb.createSheet(strSheetName);
Row row = sheet.createRow(0);
int mapColumn=mapTitle.size();
for (int i = 0; i < mapColumn; i++) {
Cell cell = row.createCell(i);
cell.setCellValue((String)mapTitle.get(i));
}
if (dataList != null && dataList.size() > 0) {
for (int i = 0; i < dataList.size(); i++) {
Row ro = ((org.apache.poi.ss.usermodel.Sheet) sheet).createRow(i + 1);
if("train_bm_info".equals(strEntityName)){
train_bm_info re = (train_bm_info) dataList.get(i);
trainBmInfo(re,ro,i,assistMap);
}
}
}
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(strFileName, "UTF-8"));
response.setContentType("application/msexcel;charset=UTF-8");
wb.write(ou);
ou.close();
}
/**
* 培训报名设置每一列
* @param p 实体
* @param ro 行
* @param i i
* @param assistMap 辅助map值
*/
@SuppressWarnings("rawtypes")
public static void trainBmInfo(train_bm_info p ,Row ro,int i,Map assistMap){
if (p != null) {
ro.createCell(0).setCellValue(1 + i);
ro.createCell(1).setCellValue(p.getStu_name());
ro.createCell(2).setCellValue(p.getSex());
ro.createCell(3).setCellValue(p.getCertnum());
ro.createCell(4).setCellValue(p.getPhone());
ro.createCell(5).setCellValue(p.getTel());
}
}
/**
* 设置导出的map第一行name
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map trainBmInfoTitle(){
Map mapTitle= new HashMap();
mapTitle.put(0, "序号");
mapTitle.put(1, "姓名");
mapTitle.put(2, "性别");
mapTitle.put(3, "身份证件号");
mapTitle.put(4, "固定电话");
mapTitle.put(5, "移动电话");
return mapTitle;
}
}
Struts1要是导出的话直接将方法声明为void就可以,这样既能导出,有没有返回值,这样非常方便,这是我写的一个公用的方法,我感觉写的还可以,假如大家有更好的方法,希望我们多多交流。