Last active
June 30, 2020 07:13
-
-
Save tekguy/4684795 to your computer and use it in GitHub Desktop.
Read an excel file using Koogra
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This example shows how to read and excel file using the Koogra library (http://sourceforge.net/projects/koogra/) | |
// Supports .xls and .xlsx example | |
public static string ReadExcelContent(string filePath) | |
{ | |
uint rowNum = 0; | |
uint colNum = 0; | |
var data = new StringBuilder(); | |
try | |
{ | |
Net.SourceForge.Koogra.IWorkbook wb; | |
string fileExt = Path.GetExtension(filePath); | |
if (string.IsNullOrEmpty(fileExt)) | |
{ | |
throw new Exception("File extension not found"); | |
} | |
if (fileExt.Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) | |
{ | |
wb = Net.SourceForge.Koogra.WorkbookFactory.GetExcel2007Reader(filePath); | |
} | |
else if(fileExt.Equals(".xls", StringComparison.OrdinalIgnoreCase)) | |
{ | |
wb = Net.SourceForge.Koogra.WorkbookFactory.GetExcelBIFFReader(filePath); | |
} | |
Net.SourceForge.Koogra.IWorksheet ws = wb.Worksheets.GetWorksheetByIndex(0); | |
for (uint r = ws.FirstRow; r <= ws.LastRow; ++r) | |
{ | |
Net.SourceForge.Koogra.IRow row = ws.Rows.GetRow(r); | |
if (row != null) | |
{ | |
string lineEnding; | |
for (uint colCount = ws.FirstCol; colCount <= ws.LastCol; ++colCount) | |
{ | |
string cellData = string.Empty; | |
if (row.GetCell(colCount) != null && row.GetCell(colCount).Value != null) | |
{ | |
cellData = row.GetCell(colCount).Value.ToString(); | |
} | |
if (colCount == ws.LastCol) | |
lineEnding = Environment.NewLine; | |
else | |
lineEnding = "\t"; //tab | |
data.Append(string.Concat(cellData, lineEnding)); | |
} | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Exception exception = ex; | |
exception.Source = string.Format("Error occured on row {0} col {1}", rowNum, colNum); | |
throw ex; | |
} | |
return data.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hello ,, this code is working fine for Excel sheets with extension of ".xlsx" i.e latest but not reading the sheets for those with extension ".xls" ... Can you plz help me out in this.
Thanks in advance... :)