【问题标题】:C# GetOleDdSchemaTable get columns from excel when sheet name has blank spaces当工作表名称包含空格时,C#GetOleDdSchemaTable 从 excel 中获取列
【发布时间】:2018-08-24 22:17:36
【问题描述】:

我正在使用 OleDb 从 Excel 电子表格中查询数据。下面的代码非常适用于名称没有空格的工作表(例如:CustomersFromGermany)。但是,对于名称中有空格的工作表,代码不会返回任何列(例如来自德国的客户)。

 public List<string> GetColumnNames(string filePath, string sheetName) // modify the parameter to be only the file path and the sheetName
    {

        List<string> columns = new List<string>();

        using (OleDbConnection connection = new OleDbConnection((filePath.TrimEnd().ToLower().EndsWith("x")) ? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
            : "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties=Excel 8.0;"))
        {
            connection.Open();


            // Attempts described below - below code snipet.


            DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, sheetName, null });

            foreach (DataRow drColumn in dt.Rows)
            {
                string s = Convert.ToString(drColumn["COLUMN_NAME"]);
                columns.Add(s);
            }
            connection.Close();
        }
        return columns;
    }

我已经尝试在调用 GetOleDbSchemaTable 之前修改 sheetName 字符串(以下是我尝试的两种方式),但没有一个解决方案有效。

第一次尝试 - 在名称 / 之间插入两个括号,还带有括号 + 单引号:

sheetName = String.Format("[{0}$]", sheetName);

sheetName = String.Format("['{0}$']", sheetName);

第二次尝试 -

 if (sheetName.Contains(' '))
       sheetName = Regex.Match(sheetName, @"(?<=')(.*?)(?=\$')", RegexOptions.None).Value + "$";

到目前为止没有任何效果。

下面是当我选择名称有空格的 sheetName 时我的 DataSet Visualiser 的屏幕截图:

【问题讨论】:

  • 请注意,ACE.OLEDB.12 驱动程序可以完美处理 .xls 文件,不需要像这样的 ConnectionString 中的条件
  • 你需要额外的单引号sheetName = String.Format("['{0}$']", sheetName);。所以你的表名应该看起来像['Customers From Germany$']
  • 我也已经尝试过,但最初忘记将其包含在问题中。我已经更新了这个问题。谢谢
  • 您的示例 $ 中的@Afonsoalb 在 ' 之后出现
  • 获取 TABLE_NAME 架构集合的结果是什么?

标签: c# excel oledb


【解决方案1】:

我有类似的代码,但从未遇到过您遇到的问题。假设我的工作表名称作为参数数组传入,我会像这样进行表名称更正:

var fixedTableNames = tableNames.Select(t => string.Format
                            ("[{0}{1}]", t, t.EndsWith("$")
                                ? ""
                                : "$")
                            ).ToArray();

【讨论】:

    【解决方案2】:

    在此处移动评论。

    你需要在表名两边加上空格,即你必须使用单引号

    'Customers From Germany$'
    

    查询中的表名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多