.net core 导入excel
程序员文章站
2024-01-21 15:19:28
...
1使用NPOI
2代码使用
[HttpPost]
public IActionResult KS_Import(IFormFile file)
{
try
{
var stream = file.OpenReadStream();//获取文件内容
var fileType = Path.GetExtension(file.FileName);//获取文件后缀 带.
DataTable dt = new DataTable();
ISheet sheet = null;
IWorkbook workbook = null;
#region 判断excel版本
//2007以上版本excel
if (fileType == ".xlsx")
{
workbook = new XSSFWorkbook(stream);
}
//2007以下版本excel
else if (fileType == ".xls")
{
workbook = new HSSFWorkbook(stream);
}
else
{
throw new Exception("传入的不是Excel文件!");
}
#endregion
sheet = workbook.GetSheetAt(0);//取第1个工作表
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);//首行
int cellCount = firstRow.LastCellNum;//列总数
for (int i = firstRow.FirstCellNum; i < cellCount; i++)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue.Trim();
if (!string.IsNullOrEmpty(cellValue))
{
DataColumn dataColumn = new DataColumn(cellValue);
dt.Columns.Add(dataColumn);
}
}
}
var Data = new List<ModelGraduateCheckImport>();
var modelGraduateCheckImport = new ModelGraduateCheckImport();
//遍历行
for (int j = sheet.FirstRowNum + 1; j <= sheet.LastRowNum; j++)
{
IRow row = sheet.GetRow(j);
if (row == null || row.FirstCellNum < 0)//编号
{
continue;
}
////遍历列
//for (int i = row.FirstCellNum; i < cellCount; i++)
//{
// ICell cellData = row.GetCell(i);
//}
if (row.GetCell(0) != null && row.GetCell(1).CellType == CellType.String)
{
modelGraduateCheckImport.ChecklistBatch = row.GetCell(0).ToString();
}
if (row.GetCell(1) != null && row.GetCell(1).CellType == CellType.String)
{
modelGraduateCheckImport.IdentityCardNo = row.GetCell(0).ToString();
}
if (row.GetCell(2) != null && row.GetCell(2).CellType == CellType.Numeric)
{
modelGraduateCheckImport.CheckCode = (int)row.GetCell(2).NumericCellValue;
}
if (row.GetCell(1).CellType == CellType.String)
{
modelGraduateCheckImport.CheckMark = row.GetCell(3).ToString();
}
Data.Add(modelGraduateCheckImport);
var jsondata = JsonConvert.SerializeObject(Data);
Console.WriteLine($"导入的数据为:{jsondata}");
}
}
else
{
throw new Exception("没有获取到Excel中的数据表!");
}
return Json(new { code = 0, msg = "导入成功" });
}
catch (Exception)
{
return Json(new { code = 0, msg = "导入成功" });
}
}