Monday 10 December 2012

Export to .csv file - Name the file on export

Introduction: It seems easy to make a file downloadable, thats what I presumed when I was assigned this task myself. As soon as I started with this I got stuck on some minor things for which later actually I spent almost a day searching and hence at the end found the solution.


Problem: I was able to create a file even download it but issue was naming the file.
I had a table data that i needed to export to ".csv" format and name the file as "resultdata-randomNo.csv" using javascript
but the issue was when downloading it was in the format of  "xxx.part" and not csv. So I tried out the following way.

Here is the view.jsp
<script type="text/javascript">
function download(){ 
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var index in array[i]) {
                line += array[i][index] + ',';
            }

            line.slice(0,line.Length-1); 

            str += line + '\r\n';

            }
var randomnumber= Math.floor(Math.random()* Math.pow(10,6) + Math.pow(10,5));
      var thisForm = document.createElement('form');
      thisForm.style.display = 'none';
      document.body.appendChild(thisForm);
      var fileName = document.createElement('input');
      fileName.type = 'hidden';
      fileName.name = 'fileName';
      fileName.value = 'resultdata-'+randomnumber;
      thisForm.appendChild(fileName);
      var dataTable = document.createElement('input');
      dataTable.type = 'hidden';
      dataTable.name = 'tableData';
      dataTable.value = str;
      thisForm.appendChild(dataTable);

      thisForm.method = 'POST';
      thisForm.action = "<%=renderResponse.encodeURL(renderRequest.getContextPath())%>/tabledata.jsp";
      thisForm.submit();
      document.body.removeChild(thisForm);

}
</script>

tabledata.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page contentType="application/octet-stream"%>
<%
    String tableData = "No records found";
    String fileName = "datatable";
    if (request.getParameter("fileName") != null
            || request.getParameter("fileName") != "") {
        fileName = request.getParameter("fileName");
    }
    if (request.getParameter("tableData") != null
            || request.getParameter("tableData") != "") {
        tableData = request.getParameter("tableData");
    }
    response.setHeader("Content-Disposition", "attachment;filename=\""
            + fileName + ".csv\"");
    out.print(tableData);
%>


The code is self-explanatory.

Hope it answers your problem also.


No comments:

Post a Comment