poi导出excel文件并提示下载

  • 格式:doc
  • 大小:40.00 KB
  • 文档页数:3

一、导入jar包:
poi-3.0.1-FINAL-20070705.jar;
poi-3.0-alpha1-20050704.jar;
二、获取List<bean>类型数据
三、利用poi生成excel文件
/**
* 生成excel文件
* @param tjxxs 写入excel的List<WorkListBean>数据
* @param xlsName 文件名称
* @param sheetName 内容标题
* @return int
*/
@SuppressWarnings("deprecation")
public int resultSetToExcel(List<WorkListBean> tjxxs,String xlsName,String sheetName) throws Exception{ if(tjxxs == null || "".equals(tjxxs)){
return 0;
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(0,sheetName,HSSFWorkbook.ENCODIN
G_UTF_16);
HSSFRow row= sheet.createRow((short)0);;
HSSFCell cell;
//写入各个字段的名称
// for(int i=1;i<=4;i++){
cell = row.createCell((short)(0));
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("序号");
cell = row.createCell((short)(1));
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("工作控制号");
cell = row.createCell((short)(2));
cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("单位名称");
cell = row.createCell((short)(3));
cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("工作类型");
int iRow=1;
//写入各条记录,每条记录对应Excel中的一行
for(int i = 0;i < tjxxs.size();i++){
WorkListBean tjxx = tjxxs.get(i);
row= sheet.createRow((short)iRow);
cell = row.createCell((short)0);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(iRow);
cell = row.createCell((short)1);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(tjxx.getJybh());
cell = row.createCell((short)2);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(tjxx.getDwmc());
cell = row.createCell((short)3);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(tjxx.getTypename());
iRow++;
}
FileOutputStream fOut = new FileOutputStream(xlsName); FileOutputStream(xlsName);
try {
workbook.write(fOut);
fOut.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fOut != null){
fOut.close();
}
}
return 1;
}
四、设置提示下载弹出框
FileInputStream fis = new FileInputStream(new File(file)); OutputStream os = response.getOutputStream();
response.setHeader("Content-Disposition","attachment;file name="+new
String(fileName.getBytes("gb2312"),"iso8859-1"));
response.setCharacterEncoding("utf-8");
int j = 0;
byte[] b = new byte[8192];
while ((j = fis.read(b, 0, 8192)) != -1)
{
os.write(b, 0, j);
}
os.flush();
fis.close();
注:fileName.getBytes("gb2312"),"iso8859-1")是解决文件名中文乱码的问题;
详见InitAction和CommonMethod文件中方法;。