我使用ExcelDataReader和ExcelDataReader.DataSet库从xlsx文件读取1700多行。最终,没有读取的记录。但是,如果我们将一个内存中的行数限制为9,则所有行数据都将正确读取。这是代码:
private IEnumerable<T> ParseImportSourceFile<T>(string fileName, byte[] file) where T : CsvClassMap
{
IEnumerable<T> records = null;
var extensionEnd = Path.GetExtension(fileName).ToLower();
switch (Path.GetExtension(fileName).ToLower())
{
case ".csv":
break;
case ".xls":
case ".xlsx":
case ".ods":
records = new List<T>();
var memoryStream = new MemoryStream(file);
var streamReader = new StreamReader(memoryStream);
var reader = ExcelReaderFactory.CreateReader(streamReader.BaseStream);
if (extensionEnd == ".xlsx")
{
reader = ExcelReaderFactory.CreateOpenXmlReader(streamReader.BaseStream);
//reader.
}
//reader.AsDataSet().
try
{
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
UseColumnDataType = true,
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
EmptyColumnNamePrefix = "Column",
UseHeaderRow = true,
}
});
if (result.Tables.Count > 0)
{
var tbl = result.Tables[0];
//grab column names into array
var columns = new DataColumn[tbl.Columns.Count];
tbl.Columns.CopyTo(columns, 0);
//grab properties of T class
var tType = typeof(T);
var properties = tType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < tbl.Rows.Count; i++)
{
//one row one record... create an instance for each row
var row = tbl.Rows[i];
var record = Activator.CreateInstance<T>();
//read all columns and try set valid property
foreach (var col in columns)
{
var prop = properties.FirstOrDefault(x => x.Name == col.ColumnName ||
(x.GetCustomAttribute<DisplayAttribute>() != null && x.GetCustomAttribute<DisplayAttribute>().Name == col.ColumnName));
if (prop != null && prop.CanWrite)
{
//
var sourceValue = row[col.ColumnName];
if(!(sourceValue is DBNull))
prop.SetValue(record, Parse(prop.PropertyType, sourceValue.ToString()));
}
}
((IList<T>)records).Add(record);
}
}
}
finally
{
if (reader != null) reader.Dispose();
if (streamReader != null) streamReader.Dispose();
if (memoryStream != null) memoryStream.Dispose();
}
break;
default:
throw new ImportException("Template is not valid.");
}
return records;
}
我对xlsx文件使用CreateOpenXmlReader方法,因为建议使用 堆栈溢出。 tbl.Rows.Count为零-来自xlsx文件中的1700多行。请帮助