HSSFWorkbook workBook =readXls(request, fileName); if(workBook==null){ return; } HSSFSheet sheet = workBook.getSheet("sheet1"); response.setHeader("Content-type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=" + encodeFileName(request, counter.getArea()+counter.getName()+"XXXXXXXX.xls")); ServletOutputStream fileOut =response.getOutputStream(); workBook.write(fileOut); fileOut.flush(); fileOut.close();
private HSSFWorkbook readXls(HttpServletRequest request,String fileName) throws IOException{ String filePath = request.getSession().getServletContext() .getRealPath(""); // filePath=ReportManageController.class.getResource("/").getPath(); InputStream inp = null; try { inp = new FileInputStream(filePath + "/" + fileName); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } HSSFWorkbook workBook=null; if(inp!=null){ workBook = new HSSFWorkbook(inp); } return workBook; }
private void setSheetCellValue(HSSFSheet sheet, int rowIndex, int colIndex, Object value,int cellType) { // HSSFComment conment=sheet.getCellComment(rowIndex, colIndex); HSSFRow row = sheet.getRow(rowIndex); HSSFCell cell = row.getCell(colIndex); cell.setCellType(cellType); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: cell.setCellValue(value.toString()); break; case Cell.CELL_TYPE_NUMERIC: cell.setCellValue(Integer.parseInt(value.toString())); break; default: cell.setCellValue(value.toString()); } }
private String encodeFileName(HttpServletRequest request, String fileName) throws UnsupportedEncodingException { String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) { return URLEncoder.encode(fileName, "UTF8"); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { return "=?UTF-8?B?"+ (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?="; } else { return fileName; } }