【问题标题】:Upload and read excel file using .NET core MVC使用 .NET core MVC 上传和读取 excel 文件
【发布时间】:2019-08-06 04:51:27
【问题描述】:

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

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

  • 确保用户上传的是 .xlsx 文件(而不是其他文件)
  • 在上传期间读取 excel 数据
  • 在数据库中保存数据

【问题讨论】:

    标签: entity-framework model-view-controller file-upload .net-core npoi


    【解决方案1】:

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

        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;}
    }
    

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

    最后在视图中,你可以有一个带有文件上传对话框的表单,并传递用户上传的文件。调用控制器的 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 }
                });
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 1970-01-01
      • 2019-04-15
      • 2018-11-08
      • 1970-01-01
      • 2023-03-04
      • 2019-06-26
      • 2018-06-23
      • 1970-01-01
      相关资源
      最近更新 更多