Adarsh Adarsh - 5 months ago 12
Javascript Question

how to add openwith and save as dialogue box while exporting to .excel on button click

I am exporting data displayed in jqgrid into .excel file by clicking button .
Here is my code for export to excel button click..

var fromdate=$('#fromdate').val();
var todate=$('#todate').val();
if(fromdate && todate)
var URL='excel.jsp?fromdate='+$('#fromdate').val()+'&todate='+$('#todate').val();
alert('Exported To Excel');


Now this button will direct to excel.jsp page .Below is my excel.jsp page code which is directly giving path to save the generated .excel file in local disk D://.Now Asper my need when the user click on export to excel button a openwith and save as dialogue box should popup which gives user ability to give desired name and save to desired position..


String datum1 = request.getParameter("fromdate");
String datum2 = request.getParameter("todate");
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdfSource.parse(datum1);
Date date2 = sdfSource.parse(datum2);
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
datum1 = sdfDestination.format(date);
datum2 = sdfDestination.format(date2);

String filename = "d:/excel.xls";
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("CallBillingSystem");

HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("calldate");
rowhead.createCell((short) 1).setCellValue("src");
rowhead.createCell((short) 2).setCellValue("dst");
rowhead.createCell((short) 3).setCellValue("dstchannel");
rowhead.createCell((short) 4).setCellValue("lastapp");
rowhead.createCell((short) 5).setCellValue("duration");
rowhead.createCell((short) 6).setCellValue("disposition");
rowhead.createCell((short) 7).setCellValue("amaflags");
rowhead.createCell((short) 8).setCellValue("cdrcost");

String strQuery = "";
ResultSet rs = null;

conexion conexiondb = new conexion();

strQuery = "SELECT * FROM cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";

rs = conexiondb.Consulta(strQuery);
int i = 1;
while ( {
HSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(rs.getString("calldate"));
row.createCell((short) 1).setCellValue(rs.getString("src"));
row.createCell((short) 2).setCellValue(rs.getString("dst"));
row.createCell((short) 3).setCellValue(rs.getString("dstchannel"));
row.createCell((short) 4).setCellValue(rs.getString("lastapp"));
row.createCell((short) 5).setCellValue(rs.getString("duration"));
row.createCell((short) 6).setCellValue(rs.getString("disposition"));
row.createCell((short) 7).setCellValue(rs.getString("amaflags"));
row.createCell((short) 8).setCellValue(rs.getString("cdrcost"));
FileOutputStream fileOut = new FileOutputStream(filename);
System.out.println("Your excel file has been generated!");

} catch (Exception ex) {



You should set several HTTP headers and write content of Excel file directly to the OutputStream of HttpServletResponse.

response.setHeader("Content-Type", "application/");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Length", String.valueOf(fileSize));
response.addHeader("Content-Disposition", String.format("attachment; filename=%s", fileName));

"Content-Type" header tells what type of stream you are sending to browser. Mime type depends on format of your Excel file. See What is correct content-type for excel files?.

"Content-Length" is not a mandatory but it allows browser to show progress of download.

"Content-Disposition" tells browser initial file name to save as (without path).

Response with this headers automatically opens "Save as…" dialogue in your browser or start download to your "Downloads" folder immediately depending on your browser settings.

Also consider using servlet instead of JSP like this: import; import; import; import; import; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class ExcelServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File tempFile = File.createTempFile(getClass().getName(), ".xls");
        try {
            FileOutputStream fos = new FileOutputStream(tempFile);
            try {
            } finally {

            response.setHeader("Content-Type", "application/");
            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Content-Length", String.valueOf(tempFile.length()));
            response.addHeader("Content-Disposition", String.format("attachment; filename=%s", tempFile.getName()));

            OutputStream outputStream = response.getOutputStream();
            FileInputStream fis = new FileInputStream(tempFile);
            try {
                int n = 0;
                byte[] buffer = new byte[1024];
                while ((n = != -1) {
                    outputStream.write(buffer, 0, n);
            } finally {
        } finally {

    private void generateExcel(OutputStream outputStream) throws IOException {
        // TODO This is stub. Place you excel generation code here
        outputStream.write("Hellol, world!".getBytes());

Update You can't download file in the way described by me using jQuery.ajax function. I usually use a hidden iframe:

    var fromdate = $('#fromdate').val();
    var todate = $('#todate').val();
    if(fromdate && todate) {
        var url = 'excel?fromdate=' + fromdate + '&todate=' + todate;
        $('#download-frame').attr('src', url);

Include in your page markup:

<iframe id="download-frame" src="" width="1" height="1" style="display: none"></iframe>