C#import excel到datagridview

时间:2017-11-02 18:32:34

标签: c# excel datagridview

我想将excel文件导入datagridview1,我收到此错误。 我该如何解决这个错误?

错误CS1061' IExcelDataReader'不包含' IsFirstRowAsColumnNames'的定义没有扩展方法' IsFirstRowAsColumnNames'接受类型' IExcelDataReader'的第一个参数。可以找到(你错过了使用指令或程序集引用吗?)

private void dosyasec_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx*", ValidateNames = true })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
            IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
           // DataSet result = reader.AsDataSet();
            reader.IsFirstRowAsColumnNames = true;
            result = reader.AsDataSet();
            comboBox1.Items.Clear();
            foreach (DataTable dt in result.Tables)
                comboBox1.Items.Add(dt.TableName);
            reader.Close();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

听起来你遇到了同样的问题:https://github.com/ExcelDataReader/ExcelDataReader/issues/261

基本上,读者配置信息现在设置不同。也许您要么从过时的示例中获取代码,要么是现有代码,并且最近更新了读取器库。无论如何,我认为您需要做的就是使用链接中提到的方法:

var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
    ConfigureDataTable = (_) => new ExcelDataTableConfiguration() {
        UseHeaderRow = true
    }
});

除非我真的搞砸了,否则这会使你现有的方法像这样:

  private void dosyasec_Click(object sender, EventArgs e)
    {
        using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx*", ValidateNames = true })
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
                IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
                var result = reader.AsDataSet(
                    new ExcelDataSetConfiguration()
                    {
                        ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = true
                        }
                    }
                );
                comboBox1.Items.Clear();
                foreach (DataTable dt in result.Tables)
                    comboBox1.Items.Add(dt.TableName);
                reader.Close();
            }
        }

    }