public class Person
{
[ExcelColumnName("姓名")]
public string? Name { get; set; }
[ExcelColumnName("性别")]
public string? Sex { get; set; }
[ExcelColumnName("年龄")]
public string? Age { get; set; }
}
[HttpPost("import")]
public IActionResult ImportExcel(IFormFile excel)
{
//内存流
var stream = new MemoryStream();
//将excel文件复制到内存流
excel.CopyTo(stream);
//在内存中查询Person并转换为集合
var list = stream.Query<Person>().ToList();
foreach (var person in list)
{
Console.WriteLine(person.Name);
Console.WriteLine(person.Sex);
Console.WriteLine(person.Age);
}
return Ok("File import successfully");
}
[HttpGet("export")]
public IActionResult ExportExcel()
{
//values 是导出的数据
var values = new[]
{
new { Column1 = "MiniExcel", Column2 = 1 },
new { Column1 = "Github", Column2 = 2}
};
//内存流
var memoryStream = new MemoryStream();
//将数据保存到内存流
memoryStream.SaveAs(values);
//设置流中的读取位置
memoryStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = "demo.xlsx"
};
}
[HttpPost("downloadExcelTemplate")]
public IActionResult DownloadExcelFromTemplatePath()
{
//模板物理路径
string templatePath = "excelTemplate.xlsx";
Dictionary<string, object> value = new Dictionary<string, object>()
{
};
MemoryStream memoryStream = new MemoryStream();
memoryStream.SaveAsByTemplate(templatePath, value);
memoryStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = "demo.xlsx"
};
}