C # Web Api - loading and reading data from excel file without saving the file

I have a WebApi that will receive an excel file uploaded by the user as multipart / form-data. I need to read the contents of this file in order to update the database. I was thinking about using EPPlus, but I cannot access the file. Here is the code

public class MyController : APIController
{
    [Route("import")]
    [HttpPost]
    public async Task<HttpResponseMessage> importFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "ERROR");

        Stream stream = await Request.Content.ReadAsStreamAsync();

        var excel = new ExcelPackage(stream);
        var workbook = excel.Workbook;

        var sheet = excel.Workbook.Worksheets.First();

        ...

}

      

The error is listed var sheet = excel.Workbook.Worksheets.First()

as there is no worksheet in the workbook (but the physical file has 2).

What am I doing wrong? Is it a flow?

I'm trying to have a separate library for each type of Excel file (.xls or .xlsx), but I can't seem to make it work with .xls files. I am using ExcelDataReader and now the code looks like this:

public async Task<HttpResponseMessage> importFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "NOT MULTIPART");

        Stream stream = await Request.Content.ReadAsStreamAsync();

        //open xlsx file            
        var excel = new ExcelPackage(stream);
        var workbook = excel.Workbook;
        try
        { 
            var sheet = excel.Workbook.Worksheets.First();

            //working fine with EPPlus for .xlsx files 
            return Request.CreateResponse(HttpStatusCode.OK, errors);                

        }catch(Exception)//open xls file
        {  
           //if its a .xls file it will throw an Exception              
        }

        //using ExcelDataReader to open .xls file
        IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
        DataSet result = excelReader.AsDataSet();

        // the DataSet is null, stream is setted as ReadOnlyStream and stream.length is throwing an ObjectDisposedException
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "erro");            
    }

      

+3


source to share


1 answer


You can use Microsoft.Interop.Excel to read the xls files, but even Microsoft turned this technique off because it is slow and not designed to work on servers. Moreover, their support has just ended.

Alternatively, you can use the EasyXLS library. You can use it to read XLS files.



Take a look at this sample code that explains how to import an Excel file into an SQL table: http://www.easyxls.com/manual/FAQ/import-excel-to-sql.html

+1


source







All Articles