将数据从数据库查询出来,在写入文件,提供下载。这个功能经常需要用到,今天做的一个功能需要将数据写入excel。但是由于自己有一段时间没有写过,自己写的时候到处找例子写,几经周折终于完成了,为了下次自己不至于遗忘,特做此笔记。这个类是用apache的一个子项目poi的类SXSSFWorkbook 实现,需要poi-3.8.jar和poi-ooxml-3.8.jar两个jar包。废话不多说,直接上代码:
public void writeInfile(List<Template> listtemp,HttpServletRequest request,
HttpServletResponse response){
String fileName="template.xls";
FileOutputStream fos = null;
List<Templatekinddetail> listkind = managerFacade.findAllTemplatekinddetail();
try{
String [] fields = new String[]{"模板名称","模板类型","模板内容"};
SXSSFWorkbook wf = new SXSSFWorkbook();
Sheet sh = wf.createSheet();
//向excel表格中,插入表格的列名
Row row= sh.createRow(0);
for(int i=0;i<fields.length;i++){
row.createCell(i).setCellValue(fields[i]);
}
// 从数据库中取出需要插入excel表格的对象
for(int j=0;j<listtemp.size();j++){
row= sh.createRow(j+1);
Template tempo = listtemp.get(j);
String temptype="";
int tempkind= tempo.getTemplatekind();
for(Templatekinddetail tempkindpo :listkind){
if(tempkindpo.getId()==tempkind){
temptype = tempkindpo.getName();
}
}
row.createCell(0).setCellValue(tempo.getName());
row.createCell(1).setCellValue(temptype);
row.createCell(2).setCellValue(tempo.getContent());
}
//将数据插入到excel表中
fos = new FileOutputStream(fileName);
wf.write(fos);
//文件下载
File file = new File(fileName);
if(file.exists()){
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[bis.available()];
fis.read(buffer);
//指定默认名(路径)
response.addHeader("Content-Disposition","attachment; filename=\""+fileName+"\"");
OutputStream os = response.getOutputStream();
os.write(buffer);
os.flush();
os.close();
bis.close();
file.delete();
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}