Send query results to Excel from ASP.NET website

2020-02-10 08:26发布

We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel. I have the application populating a DataTable, then using the datatable to create a tab delimited string. The problem is getting that to excel.

What is the best way to stream data to Excel? Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.

标签: asp.net excel
7条回答
forever°为你锁心
2楼-- · 2020-02-10 08:54

Once you have your Dataset you can convert it to an object[,] and insert it into an Excel document. Then you can save the document to disk and stream it to the user.

        //write the column headers
        for (int cIndex = 1; cIndex < 1 + columns; cIndex++)
            sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption);
        if (rows > 0)
        {

            //select the range where the data will be pasted
            Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]);

            //Convert the datatable to an object array
            object[,] workingValues = new object[rows, columns];

            for (int rIndex = 0; rIndex < rows; rIndex++)
                for (int cIndex = 0; cIndex < columns; cIndex++)
                    workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString();

            r.Value2 = workingValues;
         }
查看更多
登录 后发表回答