简体   繁体   中英

select spacific sheet in import data from Excel to database ADO.net using C#

I need to select Sheet Name When I import data from Excel To Database using ADO.net in C# that is how i Import Excel File put i can't select sheet name

OpenFileDialog op = new OpenFileDialog();
                op.Filter = "Excel Workbook| *.xls;*.xlsx;*.xlsm";
                if (op.ShowDialog() == DialogResult.Cancel)
                    return;
                FileStream stream = new FileStream(op.FileName, FileMode.Open);
                IExcelDataReader excelreader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                DataSet result = excelreader.AsDataSet();

How can I select the name of the sheet

Here's the source code from that library you're using:

    public System.Data.DataSet AsDataSet(bool convertOADateTime)
    {
        if (!_isValid) return null;

        DataSet dataset = new DataSet();

        for (int ind = 0; ind < _workbook.Sheets.Count; ind++)
        {
            DataTable table = new DataTable(_workbook.Sheets[ind].Name);

//table filling code snipped

            if (table.Rows.Count > 0)
                dataset.Tables.Add(table);
            table.EndLoadData();
        }
        dataset.AcceptChanges();
        Helpers.FixDataTypes(dataset);
        return dataset;
    }

It looks to me like that dataset it produces has N number of DataTable objects inside, each one has a table name of whatever name was given to the sheet when the constructor was called: new DataTable(_workbook.Sheets[ind].Name);

You called your DataSet result . This code would hence list out the names of the tables inside of your dataset:

foreach(DataTable dt in result.Tables)
  Console.Out.WriteLine(dt.TableName);

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