步骤
安装Microsoft.AspNetCore.Http(后续用到的IFromFile接口在此命名空间)
NuGet\Install-Package Microsoft.AspNetCore.Http -Version 2.2.2
ICountriesService.cs添加如下代码
/// <summary>
/// Uploads countries form excel file into database
/// </summary>
/// <param name="fromFile">Excel file with list of countries</param>
/// <returns>Returns number of countries added</returns>
Task<int> UploadCountriesFromExcelFile(IFormFile fromFile);
CountriesService.cs中实现方法
public async Task<int> UploadCountriesFromExcelFile(IFormFile fromFile)
{
int countriesInserted = 0;
MemoryStream memoryStream = new MemoryStream();
await fromFile.CopyToAsync(memoryStream);
using (ExcelPackage excelPackage = new ExcelPackage(memoryStream))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets["Countries"];
int rowCount = worksheet.Dimension.Rows;
for (int i = 2; i <= rowCount; i++)
{
string? cellValue = Convert.ToString(worksheet.Cells[i, 1].Value);
if (!string.IsNullOrEmpty(cellValue))
{
string countryName = cellValue;
if (_db.Countries.Where(c => c.CountryName == countryName).Count() == 0)
{
Country country = new Country()
{
CountryId = Guid.NewGuid(),
CountryName = countryName,
};
await _db.Countries.AddAsync(country);
await _db.SaveChangesAsync();
countriesInserted++;
}
}
}
}
return countriesInserted;
}
Gitee获取源码: