Struts中用Apache POI作成Excel文件,并下载

jsp 下载Excel文件

 

public ActionForward execute(ActionMapping mapping,ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  
  String fileName = "test.xls";
  
  response.reset();
  response.setContentType("application/vnd.ms-excel;charset=utf-8");
  response.setHeader("Content-Disposition","attachment; filename=/"" + fileName + "/"");

  OutputStream os = response.getOutputStream();
  
  WriteToExcel(os);
  
  os.close();
  response.flushBuffer();
  
  return null;
 }

 

 

 

private static void WriteToExcel(OutputStream os)
 {
  try
  {
   HSSFWorkbook workbook = new HSSFWorkbook();
   HSSFSheet sheet = workbook.createSheet();
   
   HSSFCellStyle hhsfCellStyle;
   //スタイルの設定
   HSSFCellStyle hhsfCellStyleYellow = workbook.createCellStyle();
   hhsfCellStyleYellow.setBorderBottom((short)1);
   hhsfCellStyleYellow.setBorderLeft((short)1);
   hhsfCellStyleYellow.setBorderRight((short)1);
   hhsfCellStyleYellow.setBorderTop(HSSFCellStyle.BORDER_DOUBLE);
   hhsfCellStyleYellow.setFillForegroundColor(HSSFColor.YELLOW.index);
   hhsfCellStyleYellow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
   
   HSSFCellStyle hhsfCellStyleWhite = workbook.createCellStyle();
   hhsfCellStyleWhite.setBorderBottom((short)1);
   hhsfCellStyleWhite.setBorderLeft((short)1);
   hhsfCellStyleWhite.setBorderRight((short)1);
   hhsfCellStyleWhite.setBorderTop(HSSFCellStyle.BORDER_DOUBLE);
   hhsfCellStyleWhite.setFillForegroundColor(HSSFColor.WHITE.index);
   hhsfCellStyleWhite.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
   
   for(int i = 1; i < 1000;i++)
   {
    if(i % 2 == 0)
    {
     hhsfCellStyle = hhsfCellStyleYellow;
    }
    else
    {
     hhsfCellStyle = hhsfCellStyleWhite;
    }
    
    HSSFRow row = sheet.createRow((short)i);
    
    for(int j = 1; j < 10;j++)
    {
     HSSFCell cell = row.createCell((short) j);
     cell.setCellType(HSSFCell.CELL_TYPE_STRING);
     
     cell.setCellStyle(hhsfCellStyle);
     
     String value = String.valueOf(i * j);
     HSSFRichTextString hts = new HSSFRichTextString(value);
     cell.setCellValue(hts);
    }   
   }
   //FileOutputStream fOut = new FileOutputStream(fileName);

   workbook.write(os);

   //fOut.flush();
   //fOut.close();
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值