2017-08-10 51 views
-2

我曾尝试这个代码,但它不工作读取Excel文件:如何使用C#

private void Load_Button_Click(object sender, EventArgs e) 
{ 
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xls", ValidateNames = true }) 
    { 
     if (ofd.ShowDialog() == DialogResult.OK) 
     { 
      System.IO.FileStream fs = File.Open(ofd.FileName, System.IO.FileMode.Open, FileAccess.Read); 
      ExcelDataReader.IExcelDataReader reader = ExcelDataReader.ExcelReaderFactory.CreateBinaryReader(fs); 
      reader.IsFirstRowAsColumnNames = true; 
      result = reader.AsDataSet(); 
      cboSheet.Items.Clear(); 

      foreach (DataTable dt in result.Tables) 
       cboSheet.Items.Add(dt.TableName); 

      reader.Close();  
     } 
    } 
} 

我似乎无法运行该代码,因为IsFirstRowAsColumnNamesAsDataSet有红色的下划线。

我发现这里https://www.youtube.com/watch?v=7X3fTnuII7c

+0

,你可以在这里使用的答案:https://stackoverflow.com/questions/15828/reading-excel-files-from -c-sharp?rq = 1 – Plasmazion

回答

2

代码从instructions for the library

安装ExcelDataReader.DataSet扩展包使用AsDataSet()方法来填充System.Data.DataSet

因此您需要一个additional library这里。

IsFirstRowAsColumnNames属性根本不存在,也许它是一个遗留项已被删除。取而代之的是,它看起来像你需要在配置上传递到AsDataSet方法,例如:

ds = reader.AsDataSet(new ExcelDataSetConfiguration() 
{ 
    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() 
    { 
     UseHeaderRow = true 
    } 
}); 
+0

我已经安装了这个。它仍然不起作用。我是C#编程的初学者。我再次卡住XD – Tramyer

+0

阅读图书馆的说明。 – DavidG

+0

正在阅读。我希望我能找到钥匙。 – Tramyer