ajax + servlet + poi 匯出Excel

來源:互聯網
上載者:User

js代碼

$(document).ready(function(){$("#btn_export").click(function(){var area = $("#s-area option:selected").text();/ar b_s_num = $("#b_s_num option:selected").text();var bill_state = $("#bill_state option:selected").text();var remarks = $("#remarks option:selected").text();window.location.href="ExportConfirmBill";/*$.ajax({url:'ExportConfirmBill',type:'post',data:{'area':area,'bill_state':bill_state,'remarks':remarks},success:function(data){window.open('ExportConfirmBill');}})*/})});

後端servlet代碼

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.setContentType("octets/stream");List<String> columns = new ArrayList<String>();List<Object> confirm_bill_lst = new ArrayList<Object>();String excelName = "賬單資訊";response.addHeader("Content-Disposition","attachment;filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1") + ".xls");ServletOutputStream out = response.getOutputStream();HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet();HSSFRow row1 = sheet.createRow(0);BillManage bm = new BillManageImpl();columns = bm.getColumns();for(int i=0;i<columns.size()-1;i++){HSSFCell cell =row1.createCell(i);cell.setCellValue(columns.get(i+1));}String area = request.getParameter("area");String bill_state = request.getParameter("bill_state");String remarks = request.getParameter("remarks");System.out.println(bill_state);confirm_bill_lst = bm.exportConfirmBill(area, bill_state, remarks);for(int i=0;i<confirm_bill_lst.size();i++){List<Object> lst =(List<Object>) confirm_bill_lst.get(i);HSSFRow row = sheet.createRow(i+1);for(int j=0;j<lst.size();j++){Cell cell = row.createCell(j);if(lst.get(j)==null){cell.setCellValue("");}else{cell.setCellValue(String.valueOf(lst.get(j)));}}}wb.write(out);out.close();wb.close();}
第一次,採用ajax的方式,發送請求並傳遞相應的參數時,後台擷取了的資料並且利用POI介面類將資料填充到Excel,但是前台用戶端並沒有出現下載提示的視窗,匯出Excel失敗。

第二次,採用提交表單的方式,直接請求,匯出成功。

經過百度,才知道

ajax返回的類型只有xml、text、json、HTML等類型,沒有流類型,因此不會彈出下載提示框。


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.