Skip to content

Instantly share code, notes, and snippets.

@conholdate-gists
Last active November 8, 2023 08:32
Show Gist options
  • Save conholdate-gists/1023a39369347f71569eb347c14cf78d to your computer and use it in GitHub Desktop.
Save conholdate-gists/1023a39369347f71569eb347c14cf78d to your computer and use it in GitHub Desktop.
Read Excel File in C# | Open and Read Data from Excel XLSX in C# .NET
// Load Excel file
Workbook wb = new Workbook("excel.xlsx");
// Get worksheet using its index
Worksheet worksheet = wb.Worksheets[0];
// Print worksheet name
Console.WriteLine("Worksheet: " + worksheet.Name);
// Get number of rows and columns
int rows = worksheet.Cells.MaxDataRow;
int cols = worksheet.Cells.MaxDataColumn;
// Loop through rows
for (int i = 0; i < rows; i++)
{
// Loop through each column in selected row
for (int j = 0; j < cols; j++)
{
// Parsing cell value
Console.Write(worksheet.Cells[i, j].Value + " | ");
}
// Print line break
Console.WriteLine(" ");
}
// Load Excel file
Workbook wb = new Workbook("excel.xlsx");
// Get all worksheets
WorksheetCollection collection = wb.Worksheets;
// Loop through all the worksheets
for (int worksheetIndex = 0; worksheetIndex < collection.Count; worksheetIndex++)
{
// Get worksheet using its index
Worksheet worksheet = collection[worksheetIndex];
// Print worksheet name
Console.WriteLine("Worksheet: " + worksheet.Name);
// Get number of rows and columns
int rows = worksheet.Cells.MaxDataRow;
int cols = worksheet.Cells.MaxDataColumn;
// Loop through rows
for (int i = 0; i < rows; i++)
{
// Loop through each column in selected row
for (int j = 0; j < cols; j++)
{
// Parsing cell value
Console.Write(worksheet.Cells[i, j].Value + " | ");
}
// Print line break
Console.WriteLine(" ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment