0

im have a weird problem whereby my functionality of exporting to excel doesnt seem to work. im using J-Query and AJAX to pass html data to a http handler which has some simple context.Response code which all seems fine. Anyway, heres my code:

// my hyperlink for user to click
<a href="#" ID="hyperLink">Click Here to Export </a>

my J-Query/AJAX code

<script type="text/javascript">
    $(document).ready(function () {
        $("#hyperLink").click(function (e) {
            var result = $('#output').html();
            var newRes = result.replace('\n', '');

            $.ajax({
                url: "ExportToExcelhandler.ashx",
                data: { 'htmlData': newRes },
                dataType: "json",
                type: "POST",
                success: function (data) {
                    alert(data);
                }
            });
        });
    });
</script>

and my handler:

public void ProcessRequest(HttpContext context)
{
    string htmlStuff = context.Request["htmlData"];
    string trimStart = "";
    string trimEnd = "";

    if (htmlStuff != null)
    {
        trimStart  = htmlStuff.Substring(75, htmlStuff.Length - 75);
        trimEnd = trimStart.Remove(trimStart.Length - 8, 8) + "";
    }

    string final= trimEnd;
    context.Response.Clear();
    context.Response.Buffer = true;
    context.Response.AddHeader("content-disposition", "attachment; filename=excelData.xls");
    context.Response.ContentType = "application/vnd.ms-excel";
    HttpResponse response = context.Response;

    context.Response.Output.Write(finalHtmlData);
    context.Response.Flush();
    context.Response.End(); 
}

-- Granted, I'm doing some weird things with replace function in my J-Query, and Substring and Remove in my handler; this is because i had to trim my html data so that only the table with the data inside it was included (caused error otherwise). The html data is just report data. So the html data is passed fine to the handler, and it goes through the ProcessRequest method fine, yet doesn't export to excel. Any help would be greatly appreciated, thanks.

3
  • anyone know how i clean up the Javascrpt code above so its more readable?? apologies, first time using this site... Commented Dec 4, 2013 at 16:29
  • Any error message in the browser or in the console of browser tools (F12 Tools, Firebug or Chrome Developer Tools)? Commented Dec 4, 2013 at 16:47
  • no error message at all im afraid...if i, say, use: <a href="ExportToExcelhandler.ashx" ID="hyperLink"> Click Here to Export proper </a> instead of <a href="#" ID="hyperLink"> Click Here to Export proper </a>, it all works fine. But of course this by-passes the J-query code which passes the html data i need to the handler... Commented Dec 4, 2013 at 17:05

1 Answer 1

1

Split this into two HTTP handlers, one to generate the Excel data and the second to retrieve the data and have a resource point at it, like this:

GenerateExcelDocument HTTP handler code:

public void ProcessRequest(HttpContext context)
{
    string htmlStuff = context.Request["htmlData"];
    var docIdentifier = this.GenerateExcelDocument(htmlStuff);

    context.Response.ContentType = "text/plain";
    context.Response.Write(docIdentifier.ToString("N"));
}

private Guid GenerateExcelDocument()
{
    var identifier = Guid.NewGuid();

    string trimStart = "";
    string trimEnd = "";

    if (htmlStuff != null)
    {
        trimStart  = htmlStuff.Substring(75, htmlStuff.Length - 75);
        trimEnd = trimStart.Remove(trimStart.Length - 8, 8) + "";
    }

    // Logic that generates your document and saves it using the identifier
    // Can save to database, file system, etc.

    return identifier;
}

Now you can call this HTTP handler, like this:

$(document).ready(function () {
    $("#hyperLink").click(function (e) {
        var result = $('#output').html();
        var newRes = result.replace('\n', '');

        $.ajax({
            url: "GenerateExcelDocument.ashx",
            data: { 'htmlData': newRes },
            dataType: "json",
            type: "POST",
            success: function (result) {
                window.location.href = '/RetrieveExcelDocument.ashx/' + result;
            }
        });
    });
});

Note: The success callback is where you can hook up the HTML resource to the file retrieval from the server (think href of the anchor tag that worked without passing data to the handler before).


Finally, we need to build the retrieval HTTP handler logic to actually get the Excel document, based upon the identifier returned from the GenerateExcelDocument HTTP handler call, like this:

RetrieveExcelDocument HTTP handler code:

public void ProcessRequest(HttpContext context)
{
    var identifier = new Guid(context.Request.Url.Segments[1]);

    // Get Excel document content from database, file system, etc. here
    var fileContent = GetExcelDocument(identifier);

    context.Response.AddHeader("content-disposition", 
                               "attachment; filename=excelData.xls");
    context.Response.ContentType = "application/vnd.ms-excel";
    context.Response.OutputStream.Write(fileContent, 0, fileContent.Length);
}
Sign up to request clarification or add additional context in comments.

6 Comments

thanks for the help Karl, unfortunately it did the same as before: i just debugged through it again fine, but no export to excel. As i commented above, if i changed my <a href to : <a href="ExportToExcelhandler.ashx" ID="hyperLink"> Click Here to Export proper </a>, it exports fine (think this might be to do with the fact that this causes a postback). but of course, this way bypasses the J-query code that passes the data to the handler...
@EoinerD - updated answer to split the creation and retrieval of the Excel document into two operations.
Thanks again for the reply. Just a few things: in the RetrieveExcelDocument handler, in the processRequest method, you reference a GetExcelDocument that I assume is for me to develop, but I'm not dealing with any DB or file system; I just want to deal with the html data that is generated into the my original '#output' div.
I see in the 'success' property that the newRes is passed in (with the html data) and window.location.href is called with the RetrieveDocument with the newRes. I've debugged this handler and the breakpoint is never reached. I appreciate this definitely the way to go to, its just im not sure how the Retrieve handler is going to get called. Thanks again.
@EoinerD - you might need to play with the URL for RetrieveExcelDocument.ashx.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.