我知道了
这是在 ASP.NET Core 和 Angular 项目中将 excel 导入 SQL 服务器
我们已经在项目的 WWWROOT 文件夹中有 (test.xlsx)excel 文件,然后执行以下代码
使用 Microsoft.AspNetCore.Hosting;
使用 Microsoft.AspNetCore.Mvc;
使用 OfficeOpenXml;
使用系统;
使用 System.Data.SqlClient;
使用 System.IO;
命名空间 ArchDVS.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ExcelController : ControllerBase
{
private readonly IHostingEnvironment _hostingEnvironment;
public ExcelController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpGet, DisableRequestSizeLimit]
[Route("Import")]
public string Import()
{
string sWebRootFolder = _hostingEnvironment.WebRootPath;
//var excelFile = new FileInfo(@"TestFile.xlsx");
string sFileName = @"test.xlsx";
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
using (var con = new SqlConnection(@"Data Source=sivan.nsp\SQLEXPRESS;Initial Catalog=DVS;Integrated Security=True;"))
{
con.Open();
try
{
using (ExcelPackage epPackage = new ExcelPackage(file))
{
var worksheet = epPackage.Workbook.Worksheets[1];
for (var row = 1; row <= worksheet.Dimension.End.Row; row++)
{
var rowValues = worksheet.Cells[row, 1, row, worksheet.Dimension.End.Column];
var cmd = new SqlCommand("INSERT INTO test(ID, Name, Gender, Salary) VALUES (@contactid, @firstname, @secondname, @age)", con);
cmd.Parameters.AddWithValue("@contactid", rowValues["A1"].Value);
cmd.Parameters.AddWithValue("@firstname", rowValues["B1"].Value);
cmd.Parameters.AddWithValue("@secondname", rowValues["C1"].Value);
cmd.Parameters.AddWithValue("@age", rowValues["D1"].Value);
cmd.ExecuteNonQuery();
}
}
return "sucessfully uploded";
}
catch (System.Exception ex)
{
return "Some error occured while importing." + ex.Message;
}
}
}
}
}