.Net Core: Reading data from CSV & Excel files

34 viewsasp.net corec++csvepplusexcel
0

Using .net core & c# here.

I have a UI from which user can upload the Excel or CSV files. Once they upload this goes to my web api which handles the reading of the data from these files and returns json.

My Api code as:

 [HttpPost("upload")]
 public async Task<IActionResult> FileUpload(IFormFile file)
 {
     JArray data = new JArray();
     using (ExcelPackage package = new ExcelPackage(file.OpenReadStream()))
     {
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        //Process, read from excel here and populate jarray
     }
      return Ok(data );
 }

In my above code I am using EPPlus for reading the excel file. For excel file it works all fine but it cannot read csv file which is the limitation of EPPlus.

I searched and found another library CSVHelper: https://joshclose.github.io/CsvHelper/ The issue with this is it does vice versa and can read from CSV but not from Excel.

Is there any library available which supports reading from both.

Or would it be possible use EPPlus only but convert uploaded CSV to excel on the fly and then read. (please note I am not storing the excel file anywhere so cant use save as to save it as excel)

Any inputs please?

–Updated – Added code for reading data from excel—

 int rowCount = worksheet.Dimension.End.Row;
 int colCount = worksheet.Dimension.End.Column;

   for (int row = 1; row <= rowCount; row++)
   {
     for (int col = 1; col <= colCount; col++)
     {
         var rowValue = worksheet.Cells[row, col].Value;
     }
   }

//With the code suggested in the answer rowcount is always 1