c# - ExcelReaderFactory,读取第一张纸

标签 c# excel

我在 C# 中使用 ExcelDataReaderFactory,以便读取我的 Excel 文件并将它们插入数据库。
现在,我正在为要使用的工作表指定 sheetname。 可以让它每次都被选为第一张吗?

这是我加载数据的方式。

public IExcelDataReader getExcelReader()
{
    // ExcelDataReader works with the binary Excel file, so it needs a FileStream
    // to get started. This is how we avoid dependencies on ACE or Interop:
    FileStream stream = File.Open(_path, FileMode.Open, FileAccess.Read);

    // We return the interface, so that
    IExcelDataReader reader = null;
    try
    {
        if (_path.EndsWith(".xls"))
        {
            reader = ExcelReaderFactory.CreateBinaryReader(stream);
        }
        if (_path.EndsWith(".xlsx"))
        {
            reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        }
        return reader;
    }
    catch (Exception)
    {
        throw;
    }
}

public IEnumerable<string> getWorksheetNames()
{
    var reader = this.getExcelReader();
    var workbook = reader.AsDataSet();
    var sheets = from DataTable sheet in workbook.Tables select sheet.TableName;
    return sheets;
}

public IEnumerable<DataRow> getData(string sheet, bool firstRowIsColumnNames = false)
{
    var reader = this.getExcelReader();
    reader.IsFirstRowAsColumnNames = firstRowIsColumnNames;
    var workSheet = reader.AsDataSet().Tables[sheet];
    var rows = from DataRow a in workSheet.Rows select a;
    return rows;
}

getData("april"); //Here I want it to be the first sheet, and not have to choose.

感谢任何建议。

最佳答案

我不知道那个图书馆。但我认为您无论如何都会将其转换为 DataSet。那么第一个工作表/表是:

DataTable firstWorkSheet = reader.AsDataSet().Tables[0];

indexer of DataTableCollection不仅仅是名称的索引重载。

所以整个方法是:

public IEnumerable<DataRow> GetFirstSheetData(bool firstRowIsColumnNames = false)
{
    var reader = this.getExcelReader();
    reader.IsFirstRowAsColumnNames = firstRowIsColumnNames;
    return reader.AsDataSet().Tables[0].AsEnumerable();
}

关于c# - ExcelReaderFactory,读取第一张纸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32521987/

相关文章:

c# - 哪个快 : Query Syntax vs. 循环

c# - 为什么 Microsoft.Office.Interop.Excel.Application.Quit() 让后台进程继续运行?

java - 在多线程系统中处理POI临时文件

excel - iReport xls 导出排除细节带?

excel - 如何编辑此 VBA 代码以接受不同的值?

c# - 如何使用 nhibernate 将数据库字段设置为服务器时间

c# - LINQ 和 ReSharper

c# - 从 c# 应用程序使用插件启动 excel 应用程序

vba - 在 VBA 中将公共(public)方法添加到用户窗体模块

c# - 编写 Windows Web 服务但不确定使用哪种语言?