Uploading Excel Data into DataTable in C#

Lawson Borges
By -
0

Uploading Excel Data into DataTable in C#

 Microsoft Excel is a widely used tool for storing and organizing data. Often, there arises a need to extract data from Excel files and work with it programmatically. In this blog post, we'll explore a generic method to upload data from an Excel file into a DataTable using C#.

Excel upload in c#

  1. using System;  
  2. using System.Data;  
  3. using System.IO;  
  4. using ClosedXML.Excel;  
  5.   
  6. public class ExcelUploader  
  7. {  
  8.     /// <summary>  
  9.     /// Converts an Excel sheet into a DataTable based on Stream input.  
  10.     /// </summary>  
  11.     /// <param name="stream">Provides a generic view of a sequence of bytes.</param>  
  12.     /// <returns>DataTable converted from an Excel sheet.</returns>  
  13.     public DataTable GetDataTableFromStream(Stream stream)  
  14.     {  
  15.         // Start reading the Excel file.  
  16.         using (XLWorkbook workbook = new XLWorkbook(stream))  
  17.         {  
  18.             IXLWorksheet worksheet = workbook.Worksheet(1);  
  19.   
  20.             bool isFirstRow = true;  
  21.   
  22.             // Range for reading the cells based on the last cell used.  
  23.             string readRange = "1:1";  
  24.   
  25.             DataTable dataTable = BindDataToDataTable(worksheet, isFirstRow, readRange);  
  26.   
  27.             return dataTable;  
  28.         }  
  29.   
  30.     }  
  31.   
  32.     #region PRIVATE METHODS.  
  33.     private static DataTable BindDataToDataTable(IXLWorksheet worksheet, bool isFirstRow, string readRange)  
  34.     {  
  35.         DataTable dataTable = new DataTable();  
  36.   
  37.         foreach (IXLRow row in worksheet.RowsUsed())  
  38.         {  
  39.             // If reading the first row (used), then add them as column names.  
  40.             if (isFirstRow)  
  41.             {  
  42.                 // Checking the last cell used for column generation in the datatable.  
  43.                 readRange = string.Format("{0}:{1}", 1, row.LastCellUsed().Address.ColumnNumber);  
  44.                 foreach (IXLCell cell in row.Cells(readRange))  
  45.                 {  
  46.                     dataTable.Columns.Add(cell.Value.ToString());  
  47.                 }  
  48.                 isFirstRow = false;  
  49.             }  
  50.             else  
  51.             {  
  52.                 // Adding a row in the datatable.  
  53.                 dataTable.Rows.Add();  
  54.                 int cellIndex = 0;  
  55.                 // Updating the values of the datatable.  
  56.                 foreach (IXLCell cell in row.Cells(readRange))  
  57.                 {  
  58.                     dataTable.Rows[^1][cellIndex] = cell.Value.ToString();  
  59.                     cellIndex++;  
  60.                 }  
  61.             }  
  62.         }  
  63.   
  64.         // If no data in the Excel file.  
  65.         if (isFirstRow)  
  66.             dataTable.Rows.Clear();  
  67.   
  68.         return dataTable;  
  69.     }  
  70.     #endregion  
  71. }  

Now, let's see how to use this ExcelUploader class in your application:

  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         // Example usage  
  6.         string excelFilePath = "path/to/your/excel/file.xlsx";  
  7.   
  8.         try  
  9.         {  
  10.             using (FileStream fs = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))  
  11.             {  
  12.                 ExcelUploader excelUploader = new ExcelUploader();  
  13.                 DataTable dataTable = excelUploader.GetDataTableFromStream(fs);  
  14.   
  15.                 // Now you can work with the DataTable as needed.  
  16.                 // Print DataTable for example:  
  17.                 PrintDataTable(dataTable);  
  18.             }  
  19.         }  
  20.         catch (Exception ex)  
  21.         {  
  22.             Console.WriteLine($"An error occurred: {ex.Message}");  
  23.         }  
  24.     }  
  25.   
  26.     static void PrintDataTable(DataTable dataTable)  
  27.     {  
  28.         foreach (DataRow row in dataTable.Rows)  
  29.         {  
  30.             foreach (var item in row.ItemArray)  
  31.             {  
  32.                 Console.Write($"{item}\t");  
  33.             }  
  34.             Console.WriteLine();  
  35.         }  
  36.     }  
  37. }  

if you are using wab api you can use below code to upload excel file

  1. public IActionResult Upload()  
  2. {  
  3.       
  4.         IFormFile formFile = Request.Form.Files[0];  
  5.   
  6.         string fileExtention = Path.GetExtension(fileName);  
  7.         string contentType = formFile.ContentType;  
  8.   
  9.         if (fileExtention == ".xlsx" && contentType == xlsxContentType)  
  10.         {  
  11.             DataTable dataTable = _excelService.ExcelToDatatable(formFile.OpenReadStream());  
  12.   
  13.               
  14.             return Ok(_genericService.GetResponse("SUCCESS", null, new Dictionary<string, string> { { "status", result } }));  
  15.         }  
  16.         else  
  17.         {  
  18.             return BadRequest(_genericService.GetResponse(CustomResponseCodes.BAD_REQUEST.ToString(), fileTypeError, null));  
  19.         }  
  20.       
  21. }  
 








Feel free to integrate this code into your application and customize it as per your requirements. This generic Excel upload utility can be a handy tool for dealing with Excel data programmatically.

Tags:

Post a Comment

0Comments

Post a Comment (0)