CSDN博客

img fengyuanfa

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

发表于2008/9/30 16:16:00  561人阅读

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

相关博文

我的热门文章

img
取 消
img