ASP.NET SQL查询结果直接到处Excel
更新:HHH   时间:2023-1-7


protected void ExportExcel(DataTable dt)
{
HttpResponse Response;
Response = System.Web.HttpContext.Current.Response;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.AppendHeader("Content-Disposition", "attachment;filename=Integral Summary.xlsx");
Response.AppendHeader("Content-Type", "application/ms-excel");
StringBuilder colHeaders = new StringBuilder();
StringBuilder lis_item = new StringBuilder();
DataRow[] myRow = dt.Select();
int cl = dt.Columns.Count;

        for (int i = 0; i < cl; i++)//獲取標題列名稱
        {
            colHeaders.Append(dt.Columns[i].ColumnName + "\t");
        }
        colHeaders.Append("\n");
        Response.Output.Write(colHeaders);
        colHeaders.Clear();
        foreach (DataRow row in myRow)//每行內容
        {
            for (int j = 0; j < cl; j++)//獲取每列內容
            {
                if (j == (cl - 1))//最後列內容換行
                {
                    lis_item.Append(row[j].ToString() + "\n");
                }
                else
                {
                    lis_item.Append(" " + row[j].ToString() + "\t");
                }
            }
            Response.Output.Write(lis_item);
            lis_item.Clear();
        }
        Response.Output.Flush();
        Response.End();
    }
返回开发技术教程...