简体   繁体   English

获取Excel工作表名称并将其添加到comboBox

[英]Getting Excel sheetname and add them to comboBox

I am trying to add a feature into my application where users can choose the sheets from the comboBox. 我正在尝试向我的应用程序中添加功能,以便用户可以从comboBox中选择工作表。 But I am hitting some bumps, I need some help! 但是我遇到了一些麻烦,我需要一些帮助! I was able to read the the excel file previously as I already sheet the default sheetname. 我已经能够读取默认工作表名称,因此以前能够读取excel文件。 But now I am able to get the sheetname into my comboBox, but I can't seem to read the excel file now? 但是现在我可以将工作表名称放入我的comboBox中,但是现在似乎无法读取excel文件了吗? Please help me 请帮我

public static DataTable ExcelToDataTable (string fileName)
        {
            using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    var result = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        UseColumnDataType = true,
                        ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = true
                        }
                    });
                    DataTableCollection table = result.Tables;
                    DataTable resultTable = table["Sheet1"];                 
                    return resultTable;
                }
            }
        }

 private void btnOpen_Click(object sender, EventArgs e)
        {

            try
            {
                using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel 2003 Worksheet|*.xls|Excel 2007 Worksheet|*.xlsx", ValidateNames = true, Multiselect = false })
                {
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                     dataGridView1.DataSource = ExcelToDataTable(ofd.FileName);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

And Now 现在

    public static DataSet ExcelToDataTable (string fileName)
            {
                using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = ExcelReaderFactory.CreateReader(stream))
                    {
                        var result = reader.AsDataSet(new ExcelDataSetConfiguration()
                        {
                            UseColumnDataType = true,
                            ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
                            {
                                UseHeaderRow = true
                            }
                        });
                        return result;
                    }
                }
            }

     private void btnOpen_Click(object sender, EventArgs e)
            {

                try
                {
                    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel 2003 Worksheet|*.xls|Excel 2007 Worksheet|*.xlsx", ValidateNames = true, Multiselect = false })
                    {
                        if (ofd.ShowDialog() == DialogResult.OK)
                        {
                            comboBox1.Items.Clear();
                            foreach (DataTable dt in ExcelToDataTable(ofd.FileName).Tables)
                            {
                                comboBox1.Items.Add(dt.TableName);
                            }
                            DataTableCollection table = ExcelToDataTable(ofd.FileName).Tables;
                            DataTable resultTable = ExcelToDataTable(ofd.FileName).Tables[comboBox1.SelectedIndex];
                            dataGridView1.DataSource = resultTable
                        }

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

May I know what went wrong? 我可以知道怎么了吗? I am getting an error of Cannot find table -1 but I can see the sheetname in the excel just not the content 我收到Cannot find table -1的错误,但我只能在Excel中看到工作Cannot find table -1而不是内容

At first use a DataSet property in your form: 首先,在表单中使用DataSet属性:

private DataSet ExcelDateSet { get; set; }

And add a method to read a table from it like this: 并添加一种从中读取表的方法,如下所示:

private DataTable GetExcelDataTable(string sheetName)
{
    if (string.IsNullOrEmpty(sheetName) || !ExcelDateSet.Tables.Contains(sheetName))
    {
         // Notify user to select a sheet-name from your ComboBox!
         // or you can return first-sheet info as default like this:
         // return ExcelDateSet.Tables[0];
    }

    return ExcelDateSet.Tables[sheetName];
}

then set its value in your btnOpen_Click like this: 然后像这样在btnOpen_Click设置其值:

ExcelDataSet = ExcelToDataTable(ofd.FileName);
dataGridView1.DataSource = GetExcelDataTable(comboBox1.SelectedText);
dataGridView1.DataBind();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用工作表名称获取我的Excel文件的FilePath - Get FilePath for my excel file with sheetname 在C#中读取具有多个工作表的Excel的Excel工作表名称 - To read excel sheetname for Excel having multiple sheet in C# 如何添加变量并将其从外部文件链接到组合框? - How to add variables and link them to a combobox from an external file? OLEDB for EXCEL-删除表[SheetName $]-不删除工作表 - OLEDB for EXCEL - Drop Table [SheetName$] - Doen't Delete Sheet 如何使用C#获取上传的excel文件的sheetname? - How to get sheetname of the uploaded excel file using C#? 如果工作表名称以编程方式包含空格,如何从工作表中获取Excel工作表 - How to get Excel Worksheet from sheets when a sheetname has spaces programatically Selenium C# 从 Excel 读取数据,用于基于 SheetName 的数据驱动测试 - Selenium C# reading data from Excel for data driven testing Based On SheetName 如何将项目(文本和值)添加到 ComboBox 并在 SelectedIndexChanged 中读取它们(SelectedValue = null) - How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null) 如何从我的DataGridView获取每个组合框的所有值并将其添加到DataTable? - How to get all values of every combobox from my DataGridView and Add them to DataTable? MVVM ComboBox 绑定并添加到组合框 - MVVM ComboBox Binding and add to combobox
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM