gpt4 book ai didi

c# - 我如何将数据表中的数据导出到 asp.net c# mvc3 中的 excel?

转载 作者:行者123 更新时间:2023-11-30 21:04:21 30 4
gpt4 key购买 nike

目前我正在尝试将数据从数据表导出到 c# asp.net mvc3 中的 excel 表。我在网上冲浪,发现了一些将数据表导出到 Excel 工作表的代码。它执行时没有任何错误。但是不会创建 excel 表。执行此操作的任何建议。

            string filename = "DownloadMobileNoExcel.xls";
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename="
+ filename + "");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";

//Convert the rendering of the gridview to a string representation
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dgGrid.RenderControl(htw);

//Open a memory stream that you can use to write back to the response
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.ASCII);

//Write the stream back to the response
Response.Write(sr.ReadToEnd());
Response.End();

最佳答案

protected void ExportToExcel(object sender, EventArgs e)
{

//Get the data from database into datatable
string strQuery = "select CustomerID, ContactName, City, PostalCode" +" from customers";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=DataTable.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

来源:http://www.aspsnippets.com/Articles/Export-DataSet-or-DataTable-to-Word-Excel-PDF-and-CSV-Formats.aspx

关于c# - 我如何将数据表中的数据导出到 asp.net c# mvc3 中的 excel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12453819/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com