Using FileHelpers to import Excel data using MVC 5

11,626

So, I decided instead to use ExcelDataReader to do my reading from Excel. It puts the stream (in the below code, test) into a DataSet that I can just manipulate manually. 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();
Share:
11,626
awh112
Author by

awh112

Full stack developer specializing in .NET, C#, and MVC.

Updated on June 14, 2022

Comments

  • awh112
    awh112 almost 2 years

    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. 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. 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? I just need to read the Excel file into the database. If not, should I be looking into a different way to handle the upload?