我在 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();
}
我是一名优秀的程序员,十分优秀!