繁体   English   中英

将GridView导出到Excel 2007

[英]Export GridView to Excel 2007

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

有人知道解决方案可以帮助我在Excel 2007中打开此gridview吗?

谢谢。

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

相反,您需要做的是使用可以为您生成它们的库来生成.xlsx文件。 例如, EPPlusOpen Office XML SDK 请注意,您需要避免使用基于Excel Interop的解决方案,因为Microsoft在服务器端不支持这些解决方案,它们将很难调试,并且会引起头痛。

顺便说一句,不要将其视为“导出GridView”。 那是一个不好的方法。 GridView是用于以HTML显示数据的UI元素。 可以将其视为“如何导出此数据?” 在您的情况下,可以将其视为导出DataSet或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

使用网格的数据源中的数据集。 之后建立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");

从添加列DataSet的comm.CommanText。 构建dataSet列结构的副本。 之后:

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

现在,您用数据填充了表格。 //注意fileName与连接字符串中的fileName相同! 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 !

将此字节返回到响应,您就拥有了excel文件。

暂无
暂无

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

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