java导出Excel例子

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

//导出Excel
public boolean exportExcel(HttpServletResponse response,List 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{  
    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;
}
    } 

 

你可能感兴趣的:(Excel,Java,OS)