如何在asp.net中创buildexcel文件?

我对asp.net开发很新

我已经介绍了用户下载button点击excel格式的asp repeater grid details 。 我已经完成了下面的代码,我使用谷歌search后

  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文件。

谁能指导我如何创build一个实际的Excel文件下载时,用户点击“下载”