【问题标题】:Excel Reader ASP.NETExcel 阅读器 ASP.NET
【发布时间】:2011-02-02 11:35:34
【问题描述】:

我在 ASP.NET 视图中声明了一个 DataGrid,我想生成一些 C# 代码以使用 Excel 电子表格 (.xlsx) 填充所述 DataGrid。这是我的代码:

<asp:DataGrid id="DataGrid1" runat="server"/>
        <script language="C#" runat="server">
            protected void Page_Load(object sender, EventArgs e)
            {
                string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\FileName.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";
                // Create the connection object
                OleDbConnection oledbConn = new OleDbConnection(connString);
                try
                {
                    // Open connection
                    oledbConn.Open();

                    // Create OleDbCommand object and select data from worksheet Sheet1
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [sheetname$]", oledbConn);

                    // Create new OleDbDataAdapter
                    OleDbDataAdapter oleda = new OleDbDataAdapter();

                    oleda.SelectCommand = cmd;

                    // Create a DataSet which will hold the data extracted from the worksheet.
                    DataSet ds = new DataSet();

                    // Fill the DataSet from the data extracted from the worksheet.
                    oleda.Fill(ds, "Something");

                    // Bind the data to the GridView
                    DataGrid1.DataSource = ds.Tables[0].DefaultView;
                    DataGrid1.DataBind();
                }
                catch
                {
                }
                finally
                {
                    // Close connection
                    oledbConn.Close();
                }
            }
        </script>

当我运行该网站时,什么都没有发生。什么给了?

【问题讨论】:

  • 您确定没有收到错误消息吗? - 你的 catch 块中没有任何代码
  • 要在 try/catch/finally 块中使用 finally,您不需要指定 catch 块......所以 try/finally 就足够了,因此如果发生任何错误,它们会冒泡......

标签: c# asp.net excel datagrid


【解决方案1】:

旧的 JET 驱动程序支持 XLSX 格式,仅支持 BIFF (XLS) 格式。

你的连接字符串需要这样的东西:

 Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\FileName.xlsx;Extended Properties="Excel 12.0;HDR=Yes;IMEX=2"

您还需要在您的网络服务器上下载并安装它:

http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多