使用 C# 和 OleDbConnection 从特定工作表的 Excel 文件中获取列名称

问题描述 投票:0回答:4

到目前为止,我已经设法获取整个Excel文件的列名,但我想做的是获取给定表(工作表)的Excel文件的列名。我该如何修改代码来实现这一目标。我已经尝试了一段时间,但没有取得积极的结果,非常感谢任何帮助。

public static List<String> ReadSpecificTableColumns(string filePath, string sheetName)
    {
        var columnList = new List<string>();
        try
        {
            var excelConnection = new OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';Extended Properties='Excel 12.0;IMEX=1'");
            excelConnection.Open();
            var columns = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);
            excelConnection.Close();

            if (columns != null)
            {
                columnList.AddRange(from DataRow column in columns.Rows select column["Column_name"].ToString());
            }

        }
        catch (Exception exception)
        {
            Console.WriteLine(exception.Message);
        }

        return columnList;
    }
c# excel oledb oledbconnection
4个回答
3
投票

您没有在代码中包含工作表名称。
您可以尝试以下代码:

var adapter = new OleDbDataAdapter("SELECT * FROM [" +sheetName + "$]", excelConnection);
var ds = new DataSet();
adapter.Fill(ds, "myTable");
DataTable data = ds.Tables["myTable"];

foreach(DataColumn  dc in data.Columns){
...
}

2
投票

使用这样的代码片段怎么样:

var adapter = new OleDbDataAdapter("SELECT * FROM [" +sheetName + "$A1:Z1]", excelConnection);
var table = new DataTable();
adapter.Fill(table);

对于“HDR=Yes”的连接字符串,它将读取第一行,目标表将包含所有列,但没有数据。


0
投票

你可以这样做:

    private void ValidateExcelColumns(string filePath)
    {            
        var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=Yes;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
        using (var conn = new OleDbConnection(connectionString))
        {
            conn.Open();

            DataTable dt = new DataTable();
            var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = "SELECT TOP 1 * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
                var adapter = new OleDbDataAdapter(cmd);
                adapter.Fill(dt);
            }

            foreach(DataColumn column in dt.Columns)
            {
                //Do something with your columns
            }
        }
    }

0
投票

我不得不去挖掘这个,因为它不是第一次点击。

这可以拉出列名:

using System;
using System.Linq;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string excelFilePath = @"C:\myexcelfile.xlsx";
            string providerString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml; HDR=YES;IMEX=1\";";
           
            List<string> columnNames = new List<string>();
            using (OleDbConnection oleConn = new OleDbConnection(String.Format(providerString, excelFilePath)))
            {
                oleConn.Open();
                DataTable schemaDT = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);
                DataRow[] shtRows = schemaDT.Select("[TABLE_NAME] = 'Sheet1$'");
                columnNames = shtRows.Select(o => o.Field<string>("COLUMN_NAME")).ToList();
            }

            Console.WriteLine(String.Join("\n", columnNames));
            Console.ReadLine();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.