gpt4 book ai didi

c# - ExcelReaderFactory,读取第一张纸

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:16 33 4
gpt4 key购买 nike

我在 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com