如何使用带有C#的OLEDB将Excel列名复制到字符串?

时间:2015-10-06 02:21:28

标签: c# excel oledb

Rookie here ...我需要从excel文件中获取列名,以便将其用作字符串。我正在使用带有OLEDB的C#。

private void CheckFiles();
{
    OleDbConnection MyConnection;
    DataSet DtSet;
    OleDbDataAdapter MyCommand;
    string file = @"C:\Users\...path...\2015.xlsm";
    MyConnection = new OleDbConnection(@"provider=Microsoft.ACE.OLEDB.12.0;Data Source='" +
                            file + "';Extended Properties=Excel 8.0;");
    MyCommand = new OleDbDataAdapter("Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = " + 
                            tab, MyConnection);
    MyConnection.Open();
    MyCommand.TableMappings.Add("Table", "Net-informations.com");
    MyConnection.Close();
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;";

ConnectionString = string.Format(ConnectionString, @"FullPathToExcelFile"); //my path replace with your actual file path

OleDbConnection conn = new OleDbConnection(ConnectionString);
conn.Open();

OleDbCommand cmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
OleDbDataAdapter oleDBAdapter = new OleDbDataAdapter();
oleDBAdapter.SelectCommand = cmdSelect;

DataSet myDataset = new DataSet();
oleDBAdapter.Fill(myDataset);
conn.Close();