简体   繁体   English

使用FileHelpers通过MVC 5导入Excel数据

[英]Using FileHelpers to import Excel data using MVC 5

I'm trying to write an application in MVC 5 that will accept a file specified by a user and upload that file information into the database. 我正在尝试在MVC 5中编写一个应用程序,该应用程序将接受用户指定的文件并将该文件信息上载到数据库中。 The file itself has multiple worksheets, which I think FileHelpers handles gracefully, but I can't find any good documentation about working with a byte array. 该文件本身有多个工作表,我认为FileHelpers可以很好地处理这些工作表,但是我找不到任何有关使用字节数组的好的文档。 I can get the file just fine, and get to my controller, but don't know where to go from there. 我可以很好地获取文件,并到达我的控制器,但不知道从那里开始。 I am currently doing this in the controller: 我目前正在控制器中执行此操作:

public ActionResult UploadFile(string filepath)
    {
        //we want to check here that the first file in the request is not null
        if (Request.Files[0] != null)
        {
            var file = Request.Files[0];


            byte[] data = new byte[file.ContentLength];

            ParseInputFile(data);
            //file.InputStream.Read(data, 0, data.Length);
        }

        ViewBag.Message = "Success!";

        return View("Index");
    }

    private void ParseInputFile(byte[] data)
    {
        ExcelStorage provider = new ExcelStorage(typeof(OccupationalGroup));

        provider.StartRow = 3;
        provider.StartColumn = 2;
        provider.FileName = "test.xlsx";
    }

Am I able to use the Request like that in conjunction with FileHelpers? 我可以与FileHelpers一起使用这样的Request吗? I just need to read the Excel file into the database. 我只需要将Excel文件读入数据库即可。 If not, should I be looking into a different way to handle the upload? 如果没有,我是否应该寻找其他方式来处理上传?

So, I decided instead to use ExcelDataReader to do my reading from Excel. 因此,我决定改用ExcelDataReader从Excel中读取内容。 It puts the stream (in the below code, test) into a DataSet that I can just manipulate manually. 它将流(在下面的代码中进行测试)放入我可以手动操作的DataSet中。 I'm sure it might not be the cleanest way to do it, but it made sense for me, and allows me to work with multiple worksheets fairly easily as well. 我敢肯定这可能不是最干净的方法,但这对我来说很有意义,并且使我也可以轻松地处理多个工作表。 Here is the snippet of regular code that I ended up using: 这是我最终使用的常规代码段:

//test is a stream here that I get using reflection
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(test);

DataSet result = excelReader.AsDataSet();

while(excelReader.Read())
{
    //process the file
}

excelReader.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM