简体   繁体   中英

How to find the name of the columns in an excel file

I was wondering how can I get the column names from an excel file and write the names inside a combobox.

This is the excel print and the names I want are in red

This is the code I am using to open the excel file:

using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xls", ValidateNames = true })
{
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
        IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);
        reader.IsFirstRowAsColumnNames = true;
        result = reader.AsDataSet();
        comboBox1.Items.Clear();

        foreach (DataTable dt in result.Tables) comboBox1.Items.Add(dt.TableName);
        reader.Close();

        string ConecçãoDB = ConfigurationManager.ConnectionStrings["ConecçaoDB"].ConnectionString;
        string Table = ConfigurationManager.AppSettings["table"];

        string ssqltable = Table;

        string ssqlconnectionstring = ConecçãoDB;

        filename = ofd.FileName;
         MessageBox.Show(Convert.ToString(filename));
        var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";

        var conexao = new System.Data.OleDb.OleDbConnection(connectionString);

        var sql = "SELECT * FROM ["+ comboBox1.SelectedText+ "$]";
        string sclearsql = "delete from " + ssqltable;
    }
}

1) include

HDR=YES

in your query string

if 1) won't work then try the following 2) include the range

   var sql = "SELECT * FROM [" + SHEET + "$" + Range + "];

where range your target range in format X1:X2 etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM