.net core 檔案上傳+匯入
阿新 • • 發佈:2022-05-31
[Route("api/[controller]")]
[ApiController]
public class UpdController : ControllerBase
{
private readonly IWebHostEnvironment env;
private readonly IUserRespository userRespository;
public UpdController(IWebHostEnvironment env, IUserRespository userRespository)
{
this.env = env;
this.userRespository = userRespository;
}
[HttpPost]
public IActionResult Upload(IFormFile formFile)
{
//先上傳 才能將內容匯入資料庫
//var file = request.Form.Files[0]
//判斷副檔名 要求只能上傳 excel 獲取副檔名 引用system.IO
//判斷副檔名為.xls(2003以前版本).xlsx(2007以後版本含2007)
var ext = Path.GetExtension(formFile.FileName);
if (ext == ".xls" || ext == ".xlsx")
{
try
{
//判斷檔案大小
//儲存路徑
var path = Path.Combine(env.ContentRootPath, "Images");
//判斷資料夾是否存在
if (!Directory.Exists(path))
{
//建立資料夾
Directory.CreateDirectory(path);
}
//檔案的名稱
var newName = DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
//把檔名和路徑合併
var pathName = Path.Combine(path, newName);
//通過流的方式傳遞檔案內容
using (var stream = new FileStream(pathName, FileMode.Create))
{
formFile.CopyTo(stream);
}
//////匯入
ImportData(pathName);
//返回當前的IP地址和埠號路徑和檔名
return Ok(new { oleName = formFile.FileName, url = "http://localhost:56405/StaticFiles/" + newName, size = formFile.Length });
}
catch (Exception)
{
throw;
}
}
else
{
return BadRequest("無效檔案");
}
}
private bool ImportData(string path)
{
try
{
//找到檔案開啟
using (var stream = System.IO.File.OpenRead(path))
{
//獲取的是一個集合
var rows = stream.Query<User>();
//呼叫批量新增的方法
return userRespository.AddBatchUser(rows);
}
}
catch (Exception)
{
throw;
}
}
}
NuGet包
Install-Package MiniExcel -Version 1.26.2
參考網站
https://gitee.com/dotnetchina/MiniExcel