Export GridView to Excel 2007

I want to export a gridview to excel 2007,the code i'm using can import to excel 2007 with the mime type application/vnd.ms-excel (excel 2003)but i get a warning msg that says "The file you are trying to open is in a different format...",with yes and no to clic,clicking in yes the file open,buy i can't have this msg for the customers.And using the mime type for excel 2007 (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)the file doesn't even open "Excel can't open the file because the format or extansion isn't valid".

This is the code i'm using right now:

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 */
        }
    }
}

Someone know a solution the can help me open in excel 2007 this gridview?

Thanks.


You are not exporting to an actual Excel format. You're creating an HTML file, and since you're providing a MIME type that Excel knows how to handle, Excel attempts to open it. Excel does know how to read basic HTML files, but it's difficult to control the formatting and you will get that warning message.

Instead what you need to do is generate your .xlsx files is use a library that can generate them for you. Examples of this would be EPPlus and Open Office XML SDK. Note you need to steer clear of using Excel Interop based solutions, as these are not supported by Microsoft on the server side, they will be difficult to debug, and they will cause headaches.

By the way, don't think of it as "exporting a GridView". That's a bad approach. A GridView is a UI element for displaying data in HTML. Think of it instead as "how do I export this data?" In your case, think of it as exporting a DataSet or XML type data.


        Response.Clear();
        Response.ContentType = "application/excel";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.BinaryWrite(objectData);//objectData is binary data
        Response.End();

Your response should be like this. I'm pretty sure that your code will not work, because you are not giving valid excel file to the Response, read about OleDbConnection

Use your DataSet from DataSource of the Grid. After that build OleDbConnection

OleDbConnection conn = new OleDbConnection();


string connectString = String.Format(
                    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR={1};'",
                    fileName, "YES");

                conn.ConnectionString = connectString;
                conn.Open();

 OleDbCommand comm = new OleDbCommand();
 comm.CommandText = string.Format("CREATE TABLE [{0}] ", "TableName");

Add the columns from the DataSet to the comm.CommanText. To build replica of the dataSet column structure. After that:

comm.Connection = conn;
comm.ExecuteNonQuery();

Now you have the table created with the same columns like your data set.

Now you should update the content

            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);

Now you filled the table with data. //be aware fileName is the same as fileName in the connection string ! FileStream fs = new FileStream(fileName, 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 !

Return this bytes to the Response and you have your excel file.

链接地址: http://www.djcxy.com/p/46860.html

上一篇: 您尝试打开的文件格式与Asp.Net中的文件扩展名所指定的格式不同

下一篇: 将GridView导出到Excel 2007