简体   繁体   English

将GridView导出到Excel 2007

[英]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". 我想将gridview导出到excel 2007,我正在使用的代码可以使用mime类型application / vnd.ms-excel(excel 2003)导入到excel 2007,但是我收到警告消息,提示“您正在尝试的文件要打开的文件格式是不同的...”,请单击“是”和“否”,单击“是”,打开该文件,购买,我无法为客户提供此味精。并且对excel 2007使用了mime类型(application / vnd .openxmlformats-officedocument.spreadsheetml.sheet)文件甚至都无法打开“ Excel无法打开文件,因为格式或扩展名无效”。

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? 有人知道解决方案可以帮助我在Excel 2007中打开此gridview吗?

Thanks. 谢谢。

You are not exporting to an actual Excel format. 您没有导出为实际的Excel格式。 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. 您正在创建HTML文件,并且由于要提供Excel知道如何处理的MIME类型,因此Excel尝试将其打开。 Excel does know how to read basic HTML files, but it's difficult to control the formatting and you will get that warning message. Excel确实知道如何读取基本的HTML文件,但是很难控制格式,并且您会收到该警告消息。

Instead what you need to do is generate your .xlsx files is use a library that can generate them for you. 相反,您需要做的是使用可以为您生成它们的库来生成.xlsx文件。 Examples of this would be EPPlus and Open Office XML SDK . 例如, EPPlusOpen 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. 请注意,您需要避免使用基于Excel Interop的解决方案,因为Microsoft在服务器端不支持这些解决方案,它们将很难调试,并且会引起头痛。

By the way, don't think of it as "exporting a GridView". 顺便说一句,不要将其视为“导出GridView”。 That's a bad approach. 那是一个不好的方法。 A GridView is a UI element for displaying data in HTML. GridView是用于以HTML显示数据的UI元素。 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. 在您的情况下,可以将其视为导出DataSet或XML类型数据。

        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 我非常确定您的代码将无法正常工作,因为您没有将有效的excel文件提供给响应,请阅读有关OleDbConnection

Use your DataSet from DataSource of the Grid. 使用网格的数据源中的数据集。 After that build OleDbConnection 之后建立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. 从添加列DataSet的comm.CommanText。 To build replica of the dataSet column structure. 构建dataSet列结构的副本。 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 ! //注意fileName与连接字符串中的fileName相同! FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); 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. 将此字节返回到响应,您就拥有了excel文件。

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

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