有人可以帮助我,如何使用Entity Core Framework在angular和asp.net核心项目中导入和导出Excel文件?
我有一个包含10个工作表的Excel文件,当我将Excel工作表导入SQL Server时,它将创建10个与工作表名称相关的表。在ASP.NET核心和角度项目中
答案 0 :(得分:-1)
我认识了他的
这是将Excel导入ASP.NET Core和Angular Project中的SQL Server
我们已经在项目的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;
}
}
}
}
}