从asp.net core 2中的excel文件上传和读取 [英] uploading and reading from an excel file in asp.net core 2

查看:930
本文介绍了从asp.net core 2中的excel文件上传和读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,Asp.Net MVC拥有此第三方库,可以轻松地从名为Excel Data Reader的excel文件中进行上传和读取.我们不需要将文件放在本地磁盘上,这很棒,因为我的应用程序需要在Azure上运行.

previously Asp.Net MVC had this third party library which easily allowed uploading and reading from an excel file called Excel Data Reader. We didn't need to have the file on the local disk, which was great because my application needs to run on Azure.

但是,我们现在正在将该功能移植到asp.net core 2,从搜索看来这是不可能的.有人知道任何允许我执行此操作的库吗?请注意,我不是在寻找从磁盘读取的解决方案.我想上传一个excel文件并直接从流中读取数据.

However we are now porting this functionality to asp.net core 2, and it seems from searching that this is not possible. Does anybody know any libraries that would allow me to do this? Please note, I am not looking for solutions that read from a disk. I want to upload an excel file and read data from the stream directly.

推荐答案

如果我们谈论的是Razor Pages,这是我今天测试的简单示例.

if we are talking about Razor Pages, here's a simple sample that I tested today..

环境:.NET Core 3.1, VS 2019

一个简单的课程

public class UserModel
{
    public string Name { get; set; }
    public string City { get; set; }
}

Index.cshtml.cs

usings..
using ExcelDataReader;

public void OnPost(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(), City = reader.GetValue(1).ToString()});
                }
            }
        }
        //users // you got the values here
}

在视图中标记

<form id="form1" method="post" enctype="multipart/form-data">
<div class="text-center">

    <input type="file" id="file1" name="file" />

</div>

<script>
    document.getElementById('file1').onchange = function () {
       document.getElementById('form1').submit();
     };
        </script>

您需要 ExcelDataReader nuget软件包,我使用的是3.6.0版本

github工作代码

这篇关于从asp.net core 2中的excel文件上传和读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆