Export HTML table to Excel - using jQuery or Java

前端 未结 9 1707
慢半拍i
慢半拍i 2020-12-06 07:13

I\'ve a HTML table on my JSP page, that I want to be exported to Excel on a button click.

What would be the best way of going about this?

(For ex., how would

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 07:23

    I also spend lot of time to convert html to excel after lot of R & D i found following easiest way.

    1. create hidden field and in that pass your html data to your servlet or controller for e.g

    2. on your button of href click call following function and pass your html data using in document.formexcel.exceldata.value and your servlet or controller in document.formstyle.action

      function exportDivToExcel() {
          document.formexcel.exceldata.value=$('#htmlbody').html();
          $("#lblReportForPrint").html("Procurement operation review report");
          document.formstyle.method='POST';
          document.formstyle.action='${pageContext.servletContext.contextPath}/generateexcel';
          document.formstyle.submit();
      }
      
    3. Now in your controller or servlet write following code

      StringBuilder exceldata = new StringBuilder();
      exceldata.append(request.getParameter("exceldata"));
      ServletOutputStream outputStream = response.getOutputStream();
      response.setContentType("application/vnd.ms-excel");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Content-Disposition", "attachment;filename=\"exportexcel.xls\"");
      outputStream.write(exceldata.toString().getBytes());
      

提交回复
热议问题