Send query results to Excel from ASP.NET website

后端 未结 7 606
温柔的废话
温柔的废话 2020-12-17 02:49

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 Ex

7条回答
  •  鱼传尺愫
    2020-12-17 03:16

    Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from here

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

提交回复
热议问题