/// <summary>
/// 读取Excel文件转成DataTable
/// </summary>
/// <param name="stream"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public DataSet ReadExcel(Stream stream, string fileName)
{
if (stream == null || stream.Length == 0)
return null;
var dataSet = new DataSet();
try
{
IWorkbook workbook = null;
string strExtension = Path.GetExtension(fileName);
if (strExtension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
workbook = new XSSFWorkbook(stream);
else if (strExtension.Equals(".xls", StringComparison.OrdinalIgnoreCase))
workbook = new HSSFWorkbook(stream);
else
{
_logger.LogWarning($"找不到 {strExtension} 文件类型 {Path.GetFileName(fileName)}");
return null;
}
foreach (var sheet in workbook)
{
if (sheet == null)
continue;
var dataTable = new DataTable(sheet.SheetName);
int rowCount = sheet.LastRowNum;
if (rowCount > 0)
{
int cellCount = 0;
for (int i = 0; i < rowCount; i++)
{
if (sheet.GetRow(i)?.LastCellNum > cellCount)
cellCount = sheet.GetRow(i).LastCellNum;
}
foreach (var item in GetTableColumn(cellCount))
{
dataTable.Columns.Add(new DataColumn(item));
}
for (int i = 0; i <= rowCount; ++i)
{
var row = sheet.GetRow(i);
if (row == null || row.FirstCellNum < 0) continue;
var dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
var cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
continue;
}
else
{
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == 14 || format == 31 || format == 57 || format == 58)
dataRow[j] = cell.DateCellValue;
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
dataSet.Tables.Add(dataTable);
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"读取Excel文件转成DataTable 异常:{ex.Message} {Path.GetFileName(fileName)}");
}
return dataSet;
}
// 调用
// ReadExcel(IFormFile.OpenReadStream,"Test.xls")