Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将GridView导出到Excel 2007_C#_Asp.net_Excel_Gridview - Fatal编程技术网

C# 将GridView导出到Excel 2007

C# 将GridView导出到Excel 2007,c#,asp.net,excel,gridview,C#,Asp.net,Excel,Gridview,我想将gridview导出到excel 2007,我正在使用的代码可以通过mime类型的应用程序/vnd.ms-excel excel 2003导入到excel 2007,但我收到一条警告消息,提示您尝试打开的文件格式不同…,clic为“是”和“否”,单击“是”打开文件,buy i can't have this msg for the customers.使用mime类型for excel 2007应用程序/vnd.openxmlformats-officedocument.spreadshe

我想将gridview导出到excel 2007,我正在使用的代码可以通过mime类型的应用程序/vnd.ms-excel excel 2003导入到excel 2007,但我收到一条警告消息,提示您尝试打开的文件格式不同…,clic为“是”和“否”,单击“是”打开文件,buy i can't have this msg for the customers.使用mime类型for excel 2007应用程序/vnd.openxmlformats-officedocument.spreadsheetml.sheet文件甚至无法打开excel无法打开文件,因为格式或扩展无效

这是我现在正在使用的代码:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Drawing;


namespace TesteFornecedores
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.BindGrid();
            }
        }

        private void BindGrid()
        {
            using (DataSet ds = new DataSet())
            {
                ds.ReadXml(Server.MapPath("~/Customers.xml"));
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }


        protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }




        protected void ExportToExcel(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;  filename=ExcelList");
            Response.Charset = "";
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter hw = new HtmlTextWriter(sw);

                //To Export all pages
                GridView1.AllowPaging = false;
                this.BindGrid();

                GridView1.HeaderRow.BackColor = Color.White;
                foreach (TableCell cell in GridView1.HeaderRow.Cells)
                {
                    cell.BackColor = GridView1.HeaderStyle.BackColor;
                }
                foreach (GridViewRow row in GridView1.Rows)
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (row.RowIndex%2 == 0)
                        {
                            cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                        }
                        else
                        {
                            cell.BackColor = GridView1.RowStyle.BackColor;
                        }
                        cell.CssClass = "textmode";
                    }
                }

                GridView1.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }
    }
}
有人知道一个解决方案可以帮我在Excel2007中打开这个gridview吗


谢谢。

您没有导出到实际的Excel格式。您正在创建一个HTML文件,由于您提供了一个Excel知道如何处理的MIME类型,Excel会尝试打开它。Excel确实知道如何读取基本HTML文件,但很难控制格式,您将收到警告消息

相反,您需要做的是生成.xlsx文件,使用一个可以为您生成这些文件的库。这方面的例子有和。注意:您需要避免使用基于Excel互操作的解决方案,因为Microsoft在服务器端不支持这些解决方案,它们将很难调试,并且会引起麻烦

顺便说一句,不要将其视为导出GridView。这是一个糟糕的方法。GridView是用于以HTML格式显示数据的UI元素。将其视为如何导出此数据?在您的情况下,可以将其视为导出数据集或XML类型的数据

        Response.Clear();
        Response.ContentType = "application/excel";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.BinaryWrite(objectData);//objectData is binary data
        Response.End();
你的回答应该是这样的。我很确定您的代码不会工作,因为您没有为响应提供有效的excel文件,请阅读关于OleDbConnection的内容

使用网格数据源中的数据集。之后,构建OLEDB连接

将数据集中的列添加到comm.CommanText。构建数据集列结构的副本。之后:

comm.Connection = conn;
comm.ExecuteNonQuery();
现在,您已经使用与数据集相同的列创建了表

现在您应该更新内容了

            OleDbDataAdapter ad = new OleDbDataAdapter(
                string.Format("SELECT * FROM [{0}]", "TableName"), conn);
            OleDbCommandBuilder builder = new OleDbCommandBuilder(ad);
            builder.QuotePrefix = "[";
            builder.QuoteSuffix = "]";

             // Saves the data set
            ad.Update(DataSetFromTheGrid);
现在您用数据填充了表。 //注意文件名与连接字符串中的文件名相同! FileStream fs=newfilestreamfilename,FileMode.Open,FileAccess.Read

            BinaryReader reader = new BinaryReader(fs);
            excelBytes = reader.ReadBytes((int)fs.Length);
            //after the returned bytes it will be good to delete the file !
将这些字节返回到响应,您就有了excel文件

            BinaryReader reader = new BinaryReader(fs);
            excelBytes = reader.ReadBytes((int)fs.Length);
            //after the returned bytes it will be good to delete the file !