从ASP.NET网站将查询结果发送到Excel

时间:2020-03-06 14:52:38  来源:igfitidea点击:

我们允许用户在我们的网站上创建即席查询。我们希望用户选择他们的条件,然后单击"提交"并将结果自动流式传输到Excel。我有填充数据表的应用程序,然后使用数据表创建制表符分隔的字符串。问题是要使它脱颖而出。

将数据流传输到Excel的最佳方法是什么?最好,我们不必让用户单击"提交"按钮后关闭一个空白窗口。

解决方案

将页面的文件类型更改为excel,仅将构建表所需的HTML流式传输到页面。从这里的代码

//for demo purpose, lets create a small datatable & populate it with dummy data
System.Data.DataTable workTable = new System.Data.DataTable();

//The tablename specified here will be set as the worksheet name of the generated Excel file. 
workTable.TableName = "Customers";
workTable.Columns.Add("Id");
workTable.Columns.Add("Name");
System.Data.DataRow workRow;

for (int i = 0; i <= 9; i++)
{
workRow = workTable.NewRow();
workRow[0] = i;
workRow[1] = "CustName" + i.ToString();
workTable.Rows.Add(workRow);
}

//...and lets put DataTable2ExcelString to work
string strBody = DataTable2ExcelString(workTable);

Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
Response.AppendHeader("Content-disposition", "attachment; filename=my.xls");
Response.Write(strBody);

我建议使用文件处理程序(.ashx),唯一的问题是从DataTable创建excel文件。有很多第三方产品可以为我们做到这一点(例如,Infragistics提供了可以做到这一点的组件)。

我强烈建议我们反对在服务器上使用Excel互操作的一件事...它非常重,因此不受支持。

如果我们创建的页面只是带有结果的表,并将页面的内容类型设置为" application / vnd.ms-excel",则输出将在Excel中。

Response.ContentType = "application/vnd.ms-excel";

如果要强制保存,请执行以下操作:

Response.AddHeader("Content-Disposition", "attachment; filename=somefilename.xls");

拥有数据集后,我们可以将其转换为object [,]并将其插入Excel文档中。然后,我们可以将文档保存到磁盘并将其流式传输给用户。

//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;
         }

我将使用.xls文件扩展名的处理程序和一个免费组件,将DataTable转换为本机xls格式。该网站http://www.csvreader.com/中的组件所做的工作超出了URL的含义。最新版本的excel将抱怨HTML格式的XLS文件。还请记住要返回的数据的大小。Web服务器应对此扩展使用压缩,并且代码应检查返回的行数是否大于excel在一个工作表中可以显示的行数;可能需要多张纸。 http://www.mrexcel.com/archive2/23600/26869.htm

我已经有了一个utils函数。将其放入数据表后,可以使用以下命令将其与Response一起导出

public static void DataTabletoXLS(DataTable DT, string fileName)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Charset = "utf-16";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        string tab = "";
        foreach (DataColumn dc in DT.Columns)
        {
            HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", ""));
            tab = "\t";
        }
        HttpContext.Current.Response.Write("\n");

        int i;
        foreach (DataRow dr in DT.Rows)
        {
            tab = "";
            for (i = 0; i < DT.Columns.Count; i++)
            {
                HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", ""));
                tab = "\t";
            }
            HttpContext.Current.Response.Write("\n");
        }
        HttpContext.Current.Response.End();
               }

请使用此代码解决问题。此代码会将excel工作表转换为文本格式。希望这可以解决问题

grdSrcRequestExport.RenderControl(oHtmlTextWriter);
    string s = "";
    s=oStringWriter.ToString().Replace("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">", "");
    s="<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=us-ascii\"><meta name=ProgId content=Excel.Sheet><meta name=Generator content=\"Microsoft Excel 11\"><table x:str border=0 cellpadding=0 cellspacing=0 width=560 style='border-collapse: collapse;table-layout:fixed;width:420pt'>"+s.ToString()+"</table></body></html>";
    //Byte[] bContent = System.Text.Encoding.GetEncoding("utf-8").GetBytes();
    Response.Write(s);