繁体   English   中英

如何在asp.net中创建excel文件?

[英]How to create excel file in asp.net?

我是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文件进​​行下载

Codeplex EPPlus http://epplus.codeplex.com/是在服务器中创建电子表格文档的好方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM