c# import data from excel code example
Example 1: how do you get data from excel
How do you do test using excel files in Java?
I use Apache POI libraries to read and write from excel file,
I add the Apache POI dependencies to my pom file.
In order to connect I use following classes.
-FileInputStream from Java. it is used to create connection to the file.
We pass the file path as constructor to it.
-WorkBook is a class that represents the excel file.
We create Workbook object using the FileInputStream object.
-Sheet represents a single sheet from the excel file.
We create sheet using Workbook object. We can create
worksheet using the 0 based index.
public String readExcel(String path, String sheetName,
int rowNum, int colNum) {
try {
FileInputStream file = new FileInputStream(path);
Workbook book = WorkbookFactory.create(file);
Sheet sheet = book.getSheet(sheetName);
Row row = sheet.getRow(rowNum);
Cell cell = row.getCell(colNum);
String cellData = cell.toString();
return cellData;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
How to get row and column numbers:
int rowCount = sheet.getLastRowNum()+1; ==> why we add
Because row num starts from 0.
int colCount = sheet.getRow(0).getLastCellNum();
String sheetName = workSheet.getSheetName();
Example 2: object to excel c#
maybe you could try use Infodinamica.Framework.Expotable package, hosted in Nuget.
With it, you could do something like this
List<EmployeeData> query = data.Where(x => x.Field<string>("First_Name") != string.Empty).Select(x =>
new EmployeeData
{
empID = x.Field<double>("EMPLOYEE"),
firstName = x.Field<string>("First_Name"),
lastName = x.Field<string>("Last_Name"),
JobCategory = x.Field<string>("Job Title"),
StartDate = x.Field<Nullable<DateTime>>("Hire Dt"),
EndDate = x.Field<Nullable<DateTime>>("Term Dt"),
TermReason = x.Field<string>("Term Reason"),
PeggedUID = x.Field<Nullable<double>>("Pegged UserID"),
UpdateDate = x.Field<Nullable<DateTime>>("Last Updated")
}).ToList();
IExportEngine engine = new ExcelExportEngine();
engine.AddData(EmployeeData);
MemoryStream memory = engine.Export();
You can install with nuget command:
Install-Package Infodinamica.Framework.Exportable
The only problem, documentation is in spanish.
The project page is here
Export example (in spanish) is here
It also enable import files (in spanish) here