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();
  }
 }

 

 

發佈了28 篇原創文章 · 獲贊 1 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章