【发布时间】:2013-04-05 11:07:57
【问题描述】:
我尝试将网格视图数据传输到 excel ......但是输出是一个空白的 excel 表。如何解决这个问题?是否有任何代码可以将网格视图值传输到带有数据库的 excel 表?
protected void btnexcel_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
gvdetails.HeaderRow.Cells[0].Style.Add("background-color", "green");
gvdetails.HeaderRow.Cells[1].Style.Add("background-color", "green");
gvdetails.HeaderRow.Cells[2].Style.Add("background-color", "green");
for (int i = 0; i < gvdetails.Rows.Count;i++ )
{
GridViewRow row = gvdetails.Rows[i];
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
}
}
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
【问题讨论】:
-
你在这里遇到什么错误?
-
@Ratna :正在生成的 Excel 工作表是空白的。请正确阅读要求。
-
希望您知道这不是 excel 导出,您正在提供 html 表格并以错误的内容类型欺骗浏览器作为响应。使用这种方法可以解决许多问题。 stackoverflow.com/a/10245406/351383
-
几乎所有的答案都在这里写一个(HtmlTextWriter)字符串或有互操作代码。两者都不要使用。这将导致您稍后在 DateTime 和 Decimal 格式方面出现问题。 Excel 也会发出警告,因为您生成的不是“真正的”Excel 文件,而是扩展名为 .xls 的 HTML 页面。开始使用专门的库来创建 Excel 文件,例如 EPPlus。 Example here 和 here.