如何在angular和asp.net核心项目中导入和导出excel

问题描述 投票:-1回答:1

谁能帮助我,如何使用Entity Core Framework在angular和asp.net核心项目中导入和导出excel文件?

我有一个包含10张的Excel文件,当我将Excel工作表导入SQL服务器时,它将创建10个与工作表名称相关的表。在ASP.NET核心和角度项目中

angular asp.net-core
1个回答
-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;
            }
        }
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.