使用 .NET Core MVC 上传和读取 excel 文件

Upload and read excel file using .NET core MVC

我在 .NET Core 中使用 NPOI 实现了读取 excel 文件的算法。现在我想要的是在网络应用程序中上传一个 excel 文件并在上传期间读取 excel 文件并将其保存到数据库中。

我对应该如何处理模型、视图和控制器感到有点困惑。以下是优化后的需求列表:

你的控制器可以是这样的:

    public ActionResult Import(System.Web.HttpPostedFileBase uploadFile)
    {
        if (uploadFile != null)
            {
                if (uploadFile.ContentLength > 0)
                {
                    var fileExtension = Path.GetExtension(uploadFile.FileName);
                    if (fileExtension.ToLower().Equals(".xlsx"))
                    {
                        BinaryReader b = new BinaryReader(uploadFile.InputStream);
                        int count = uploadFile.ContentLength;
                        byte[] binData = b.ReadBytes(count);
                        using (MemoryStream stream = new MemoryStream(binData))
                        {
                            //call the service layer to read the data from stream
                        }
                     }
                  }
             }
    }

而你的服务层就是你已经想出来的,用NPOI来读。

根据您从 excel 文件中读取的数据,您的模型可能是这样的:

public class Product
{
    public int ProductID {get; set;}
    public string Name {get; set;}
    public decimal Price {get; set;}
}

在数据库中,您可以有一个存储过程,它可以使用用户定义的 table 类型获取多行数据。在读取服务层中的数据后,您可以从存储库调用此存储过程。

最后在视图中,您可以有一个带有文件上传对话框的表单,并传递用户上传的文件。 Javascript 调用控制器可能是这样的:

function x () {
            var inputdata = null;
            var form = $('#__ImportFileForm');
            var token = $('input[name="__RequestVerificationToken"]', form).val();
            var fd = new FormData();
            fd.append("__RequestVerificationToken", token);
            fd.append("uploadFile", $("#uploadFile")[0].files[0]);
            inputdata = fd;
            inputdata.skipAjaxPrefilter = true;

            $.ajax({
                type: "Post",
                url: url,
                data: inputdata,
                processData: false,
                contentType: false,
                traditional: true,
                async: true,
                success: function(data) { //do what you want },
                error: function(data, ajaxOptions, thrownError) { //do what you want }
            });
}

希望这能回答您所有的问题!