【问题标题】:Importing Any Excel Spreadsheet into a DataGridView - C#将任何 Excel 电子表格导入 DataGridView - C#
【发布时间】:2012-07-10 15:56:23
【问题描述】:

我有一个将 Excel 电子表格导入数据网格视图的程序。我写的代码如下:

try
                {
                    OleDbConnectionStringBuilder connStringBuilder = new OleDbConnectionStringBuilder();
                    connStringBuilder.DataSource = file;
                    connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
                    connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX1");

                    DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

                    DbDataAdapter adapter = factory.CreateDataAdapter();

                    DbCommand selectCommand = factory.CreateCommand();
                    selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";

                    DbConnection connection = factory.CreateConnection();
                    connection.ConnectionString = connStringBuilder.ConnectionString;

                    selectCommand.Connection = connection;

                    adapter.SelectCommand = selectCommand;

                    data = new DataSet();

                    adapter.Fill(data);

                    dataGridView1.DataSource = data.Tables[0].DefaultView;

                }
                catch (IOException)
                {

                }

行 "selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";"从具有该名称的工作表中获取数据。我想知道如何让这个程序打开一个带有任何工作表名称的 excel 文档。一个我可能不知道的。

【问题讨论】:

    标签: c# excel datagridview dataset


    【解决方案1】:

    您可以像这样获取所有工作表的名称..

    public string[] GetExcelSheetNames(string excelFileName)
    {
            OleDbConnection con = null;
            DataTable dt = null;
            String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";
            con= new OleDbConnection(conStr);
            con.Open();
            dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    
            if (dt == null)
            {
                return null;
            }
    
            String[] excelSheetNames = new String[dt.Rows.Count];
            int i = 0;
    
            foreach (DataRow row in dt.Rows)
            {
                excelSheetNames[i] = row["TABLE_NAME"].ToString();
                i++;
            }
    
            return excelSheetNames;
    }
    

    【讨论】:

    • 虽然excel文件有多个工作表。
    • 我认为可能是“foreach”语句。
    • 当我调试时,它似乎完全跳过了 foreach 语句,只返回一个“null”字符串[]...嗯...
    猜你喜欢
    • 2011-08-09
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2010-09-15
    • 2014-07-22
    • 1970-01-01
    相关资源
    最近更新 更多