java导出Excel

来源:互联网 发布:易观智库产业数据库 编辑:程序博客网 时间:2024/04/30 14:53

//在service层写的,在action直接调用此方法就行了

//导出Excel
public boolean exportExcel(HttpServletResponse response,List<cityinfo> list)
    {  
try
{
OutputStream os = response.getOutputStream();// 取得输出流  
        response.reset();// 清空输出流  
        response.setHeader("Content-disposition", "attachment; filename=fine.xls");// 设定输出文件头  
        response.setContentType("application/msexcel");// 定义输出类型
       
        WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件  
        String tmptitle = "财务报表"; // 标题  
        WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称 
       
// 设置excel标题  
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,WritableFont.BOLD,
                       false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);  
WritableCellFormat wcfFC = new WritableCellFormat(wfont);
wcfFC.setBackground(Colour.AQUA);
wsheet.addCell(new Label(1, 0, tmptitle, wcfFC));  
wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14,WritableFont.BOLD,
                   false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);  
wcfFC = new WritableCellFormat(wfont); 

// 开始生成主体内容                  
wsheet.addCell(new Label(0, 2, "城市代码"));  
wsheet.addCell(new Label(1, 2, "城市名")); 

for(int i=0;i<list.size();i++)   <br="">{  
    wsheet.addCell(new Label(0, i+3, list.get(i).getCityid()));   //数据库的城市代码字段
    wsheet.addCell(new Label(1, i+3, list.get(i).getName()));  //数据库的城市名字段

   
}          
// 主体内容生成结束          
wbook.write(); // 写入文件  
wbook.close();  
os.close(); // 关闭流
return true;
}
catch(Exception ex)
{
ex.printStackTrace();
return false;
}
    } 

 

原创粉丝点击