我是asp.net开发的新手
我已经让用户在点击按钮时以excel格式下载asp repeater grid details
。我用谷歌搜索后得到的代码完成了
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ExcelExport.xls");
for (int i = 0; i < RptMasterData.Items.Count; i++)
{
Table tbl = (Table)RptMasterData.Items[i].FindControl("tblTest");
tbl.Style.Add("background-color", "#FF9900");
GridView gvAllocation = (GridView)RptMasterData.Items[i].FindControl("gvAllocation");
gvAllocation.HeaderRow.Style.Add("background-color", "#95c556");
int j = 1;
foreach (GridViewRow gvrow in gvAllocation.Rows)
{
gvAllocation.BackColor = System.Drawing.Color.White;
if (j <= gvAllocation.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
}
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
RptMasterData.RenderControl(hw);
Response.Write("<table>");
Response.Output.Write(sw.ToString());
Response.Write("<table>");
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Close();
该文件作为excel文件下载。但是当我尝试在MS office中打开文件时,我收到错误消息
当我尝试在Ms-office中编辑和保存文件时出现问题。然后它显示以下警告
所以我只是试着在文本编辑器中打开它,发现下载的文件是一个HTML文件,其中包含所需的数据,而不是excel文件。
任何人都可以指导我如何创建实际的Excel文件,以便在用户点击时下载&#34;下载&#34;