以下的java使用的框架是Jfinal.
1. 创建流和工作薄.
ServletOutputStream out = null;
HSSFWorkbook workbook =null;
try {
workbook = new HSSFWorkbook();
2. 创建工作表.
HSSFSheet sheet = workbook.createSheet("sheet1");
3.创建第一行的标头.
/*第一行*/
HSSFRow first_row = sheet.createRow(0);
first_row.createCell(0).setCellValue("序号");
first_row.createCell(1).setCellValue("日期");
first_row.createCell(2).setCellValue("时限");
first_row.createCell(3).setCellValue("标题");
first_row.createCell(4).setCellValue("程度");
first_row.createCell(5).setCellValue("编号");
first_row.createCell(6).setCellValue("备注");
4. 获取数据.
/**获取数据b*/
List<Record> list= service.getListByParams(param1, param2, status,search,...);
5.数据回填.
int c = 1;//从第二行开始填数据
for(Record item:list) {
HSSFRow row = sheet.createRow(c);
row.createCell(0).setCellValue(c);//序号从1开始
row.createCell(1).setCellValue(DateUtils.date2Str(item.getDate("createDate"), "yyy年MM月dd日"));
row.createCell(2).setCellValue(DateUtils.date2Str(item.getDate("endTime"), "yyy年MM月dd日"));
row.createCell(3).setCellValue(item.getStr("title"));
row.createCell(4).setCellValue(item.getInt("num"));
row.createCell(5).setCellValue(model.getNum());
row.createCell(6).setCellValue(model.getRemark());
c++;
}
6. 设置响应头并写出.
HttpServletResponse response = getResponse();//获取响应
response.setContentType("application/msexcel");//
response.setCharacterEncoding("UTF-8");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String today = sdf.format(new Date());
String filename = "XXX数据导出"+today+".xls";//文件名
response.addHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("GBK"), "ISO8859-1") + "");
out = response.getOutputStream();
workbook.write(out);
renderNull();
7.最后记得关闭流.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(workbook!=null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}