java下載excel範例_使用POI進行Excel檔案下載的範例工程

packagecom.heyang.action;importjava.io.BufferedOutputStream;importjavax.servlet.ServletException;importjavax.servlet.ServletOutputStream;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importcom.heyang.service.DownloadService;/*** POI下載的Servlet

*@authorheyang

**/publicclassDownloadServletextendsHttpServlet {privatestaticfinallongserialVersionUID=56890894234786L;publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, java.io.IOException {

String fileName="download.xls";

response.setHeader("Content-disposition","attachment; filename="+fileName);//設定輸出檔案頭response.setContentType("application/msexcel");//定義輸出型別try{introwCount=Integer.parseInt(request.getParameter("rowCount"));//表頭行String[] headers=newString[]{"更新ID","賬期","基站編號","基站名稱","站點狀態","部門名稱","站點型別","佔用型別","預提(元)","未核銷金額","上期未核銷","開始月份","結束月份","上期抄表數","本期抄表數","電價","電量","本期報賬(元)","補提(元)","預提匯總(元)","成本中心","專業","本期報賬單號","基站類別","線損"};

DownloadService service=newDownloadService();

HSSFWorkbook workbook=service.generateWorkbook(rowCount, headers.length);

ServletOutputStream out=response.getOutputStream();

BufferedOutputStream bos=newBufferedOutputStream(out);

workbook.write(bos);

bos.flush();

bos.close();

}catch(Exception ex){

ex.printStackTrace();

}return;

}publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, java.io.IOException {

doPost(request, response);

}

}