【问题标题】:how to read excel file in memory (without saving it in disk) and return its content dotnet core如何读取内存中的excel文件(不保存在磁盘中)并返回其内容 dotnet core
【发布时间】:2020-04-20 13:53:41
【问题描述】:

我正在使用 dotnet 核心开发 webApi,该核心从 IFormFile 获取 excel 文件并读取其内容。我正在关注文章 https://levelup.gitconnected.com/reading-an-excel-file-using-an-asp-net-core-mvc-application-2693545577db 正在做同样的事情,只是这里的文件存在于服务器上,而我的文件将由用户提供。

代码如下:

  public IActionResult Test(IFormFile file)
        {
           List<UserModel> users = new List<UserModel>();
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            using (var stream = System.IO.File.Open(file.FileName, FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {    
                    while (reader.Read()) //Each row of the file
                    {
                        users.Add(new UserModel
                        {
                            Name = reader.GetValue(0).ToString(),
                            Email = reader.GetValue(1).ToString(),
                            Phone = reader.GetValue(2).ToString()
                        });
                    }
                }
            }
            return Ok(users);
        }
    }

当 system.IO 尝试打开文件时,由于路径不存在,它找不到路径。如何获取文件路径(根据用户选择的文件而有所不同)?还有其他方法可以实现吗?

PS:我不想先上传服务器上的文件,然后再读取。

【问题讨论】:

    标签: file-upload .net-core file-read webapi


    【解决方案1】:

    您正在使用file.FileName 属性,它指的是浏览器发送的文件名。很高兴知道,但还不是服务器上的真实文件。您必须使用CopyTo(Stream) 方法来访问数据:

    public IActionResult Test(IFormFile file)
    {
        List<UserModel> users = new List<UserModel>();
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        using (var stream = new MemoryStream())
        {
            file.CopyTo(stream);
            stream.Position = 0;
            using (var reader = ExcelReaderFactory.CreateReader(stream))
            {
                while (reader.Read()) //Each row of the file
                {
                    users.Add(new UserModel{Name = reader.GetValue(0).ToString(), Email = reader.GetValue(1).ToString(), Phone = reader.GetValue(2).ToString()});
                }
            }
        }
    
        return Ok(users);
    }
    

    Reference

    【讨论】:

    • here's 是一个链接,可能会有所帮助
    猜你喜欢
    • 2017-09-08
    • 2022-12-06
    • 2016-07-26
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多