Export a large data query (60k+ rows) to Excel

I created a reporting tool as part of an internal web application. The report displays all results in a GridView, and I used JavaScript to read the contents of the GridView row-by-row into an Excel object. The JavaScript goes on to create a PivotTable on a different worksheet.

Unfortunately I didn't expect that the size of the GridView would cause overloading problems with the browser if more than a few days are returned. The application has a few thousand records per day, let's say 60k per month, and ideally I'd like to be able to return all results for up to a year. The number of rows is causing the browser to hang or crash.

We're using ASP.NET 3.5 on Visual Studio 2010 with SQL Server and the expected browser is IE8. The report consists of a gridview that gets data from one out of a handful of stored procedures depending on which population the user chooses. The gridview is in an UpdatePanel:

<asp:UpdatePanel ID="update_ResultSet" runat="server">
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="btn_Submit" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="pnl_ResultSet" runat="server" Visible="False">
    <div runat="server" id="div_ResultSummary">
        <p>This Summary Section is Automatically Completed from Code-Behind</p>
    </div>
        <asp:GridView ID="gv_Results" runat="server" 
            HeaderStyle-BackColor="LightSkyBlue" 
            AlternatingRowStyle-BackColor="LightCyan"  
            Width="100%">
        </asp:GridView>
    </div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>

I was relatively new to my team, so I followed their typical practice of returning the sproc to a DataTable and using that as the DataSource in the code behind:

    List<USP_Report_AreaResult> areaResults = new List<USP_Report_AreaResult>();
    areaResults = db.USP_Report_Area(ddl_Line.Text, ddl_Unit.Text, ddl_Status.Text, ddl_Type.Text, ddl_Subject.Text, minDate, maxDate).ToList();
    dtResults = Common.LINQToDataTable(areaResults);

    if (dtResults.Rows.Count > 0)
    {
        PopulateSummary(ref dtResults);
        gv_Results.DataSource = dtResults;
        gv_Results.DataBind();

(I know what you're thinking! But yes, I have learned much more about parameterization since then.)

The LINQToDataTable function isn't anything special, just converts a list to a datatable.

With a few thousand records (up to a few days), this works fine. The GridView displays the results, and there's a button for the user to click which launches the JScript exporter. The external JavaScript function reads each row into an Excel sheet, and then uses that to create a PivotTable. The PivotTable is important!

function exportToExcel(sMyGridViewName, sTitleOfReport, sHiddenCols) {
//sMyGridViewName = the name of the grid view, supplied as a text
//sTitleOfReport = Will be used as the page header if the spreadsheet is printed
//sHiddenCols = The columns you want hidden when sent to Excel, separated by semicolon (i.e. 1;3;5).
//              Supply an empty string if all columns are visible.

var oMyGridView = document.getElementById(sMyGridViewName);

//If no data is on the GridView, display alert.
if (oMyGridView == null)
    alert('No data for report');
else {
    var oHid = sHiddenCols.split(";");  //Contains an array of columns to hide, based on the sHiddenCols function parameter
    var oExcel = new ActiveXObject("Excel.Application");
    var oBook = oExcel.Workbooks.Add;
    var oSheet = oBook.Worksheets(1);
    var iRow = 0;
    for (var y = 0; y < oMyGridView.rows.length; y++)
    //Export all non-hidden rows of the HTML table to excel.
    {
        if (oMyGridView.rows[y].style.display == '') {
            var iCol = 0;
            for (var x = 0; x < oMyGridView.rows(y).cells.length; x++) {
                var bHid = false;
                for (iHidCol = 0; iHidCol < oHid.length; iHidCol++) {
                    if (oHid[iHidCol].length !=0 && oHid[iHidCol] == x) {
                        bHid = true;
                        break; 
                    } 
                }
                if (!bHid) {
                    oSheet.Cells(iRow + 1, iCol + 1) = oMyGridView.rows(y).cells(x).innerText;
                    iCol++;
                }
            }
            iRow++;
        }
    }

What I'm trying to do: Create a solution (probably client-side) that can handle this data and process it into Excel. Someone might suggest using the HtmlTextWriter, but afaik that doesn't allow for automatically generating a PivotTable and creates an obnoxious pop-up warning....

What I've tried:

  • Populating a JSON object -- I still think this has potential but I haven't found a way of making it work.
  • Using a SQLDataSource -- I can't seem to use it to get any data back out.
  • Paginating and looping through the pages -- Mixed progress. Generally ugly though, and I still have the problem that the entire dataset is queried and returned for each page displayed.
  • Update: I'm still very open to alternate solutions, but I've been pursuing the JSON theory. I have a working server-side method that generates the JSON object from a DataTable. I can't figure out how to pass that JSON into the (external) exportToExcel JavaScript function....

        protected static string ConstructReportJSON(ref DataTable dtResults)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("var sJSON = [");
            for (int r = 0; r < dtResults.Rows.Count; r++)
            {
                sb.Append("{");
                for (int c = 0; c < dtResults.Columns.Count; c++)
                {
                    sb.AppendFormat(""{0}":"{1}",", dtResults.Columns[c].ColumnName, dtResults.Rows[r][c].ToString());
                }
                sb.Remove(sb.Length - 1, 1); //Truncate the trailing comma
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("];");
            return sb.ToString();
        }
    

    Can anybody show an example of how to carry this JSON object into an external JS function? Or any other solution for the export to Excel.


    I would try to use displaytag to display the results. You could set it up display a certain number per page, which should solve your overloading issue. Then, you can set displaytag to allow for an Excel export.


    We typically handle this with an "Export" command button which is wired up to a server side method to grab the dataset and convert it to CSV. Then we adjust the response headers and the browser will treat it as a download. I know this is a server side solution, but you may want to consider it since you'll continue having timeout and browser issues until you implement server side record paging.


    Almost a week and a half since I began this problem, I've finally managed to get it all working to some extent. I'll wait temporarily from marking an answer to see if anybody else has a more efficient, better 'best practices' method.

    By generating a JSON string, I've divorced the JavaScript from the GridView. The JSON is generated in code behind when the data is populated:

        protected static string ConstructReportJSON(ref DataTable dtResults)
        {
            StringBuilder sb = new StringBuilder();
            for (int r = 0; r < dtResults.Rows.Count; r++)
            {
                sb.Append("{");
                for (int c = 0; c < dtResults.Columns.Count; c++)
                {
                    sb.AppendFormat(""{0}":"{1}",", dtResults.Columns[c].ColumnName, dtResults.Rows[r][c].ToString());
                }
                sb.Remove(sb.Length - 1, 1); //Truncate the trailing comma
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            return String.Format("[{0}]", sb.ToString());
        }
    

    Returns a string of data such as

    [ {"Caller":"John Doe", "Office":"5555","Type":"Incoming", etc},

    {"Caller":"Jane Doe", "Office":"7777", "Type":"Outgoing", etc}, {etc} ]

    I've hidden this string by assigning the text to a Literal in the UpdatePanel using:

        <div id="div_JSON" style="display: none;">
                <asp:Literal id="lit_JSON" runat="server" /> 
        </div>
    

    And the JavaScript parses that output by reading the contents of the div:

    function exportToExcel_Pivot(sMyJSON, sTitleOfReport, sReportPop) {
         //sMyJSON = the name, supplied as a text, of the hidden element that houses the JSON array.
         //sTitleOfReport = Will be used as the page header if the spreadsheet is printed.
         //sReportPop = Determines which business logic to create a pivot table for.
    
    var sJSON = document.getElementById(sMyJSON).innerHTML;
    var oJSON = eval("(" + sJSON + ")");
    
     //    DEBUG Example Test Code
     //    for (x = 0; x < oJSON.length; x++) {
     //        for (y in oJSON[x])
     //            alert(oJSON[x][y]); //DEBUG, returns field value
     //            alert(y); //DEBUG, returns column name
     //    }
    
    
    //If no data is in the JSON object array, display alert.
    if (oJSON == null)
        alert('No data for report');
    else {
        var oExcel = new ActiveXObject("Excel.Application");
        var oBook = oExcel.Workbooks.Add;
        var oSheet = oBook.Worksheets(1);
        var oSheet2 = oBook.Worksheets(2);
        var iRow = 0;
        var iCol = 0;
    
            //Take the column names of the JSON object and prepare them in Excel
            for (header in oJSON[0])
            {
                oSheet.Cells(iRow + 1, iCol + 1) = header;
                iCol++;
            }
    
            iRow++;
    
            //Export all rows of the JSON object to excel
            for (var r = 0; r < oJSON.length; r++)
            {
                iCol = 0;
                for (c in oJSON[r]) 
                        {
                            oSheet.Cells(iRow + 1, iCol + 1) = oJSON[r][c];
                            iCol++;
                        } //End column loop
                iRow++;
            } //End row
    

    The string output and the JavaScript 'eval' parsing both work surprisingly fast, but looping through the JSON object is a little slower than I'd like.

    I believe that this method would be limited to around 1 billion characters of data -- maybe less depending how memory testing works out. (I've calculated that I'll probably be looking at a maximum of 1 million characters per day, so that should be fine, within one year of reporting.)

    链接地址: http://www.djcxy.com/p/21334.html

    上一篇: “双”和“双”之间的区别

    下一篇: 将大型数据查询(60k +行)导出到Excel