There are multiple methods in HuLib for reading excel files. The latest addition is the BufferedExcelReader. BufferedExcelReader is meant to replace older methods as it is much much more performant. It achieves this by grabbing all excel data in bulk at the beginning and then providing methods to interact with the reader directly to get data out.
To create an instance, just call the constructor with the filename:
BufferedExcelReader reader = new BufferedExcelReader(fileName);
Now you are ready to read from it! If you want to switch the sheet you are reading you can use:
reader.GoToSheet("MySheetName");
Note that initially, the sheet will be the active workbook sheet.
There are two main ways to do the reading.
1. Using the reader
This is convenient when column numbers can change and you want to read data row by row and not have to keep track of the position manually:
string[] readLine = reader.ReadStrings(); object[] readData = reader.ReadLine();
ReadStrings() will convert everything to a string while ReadLine() will give you the raw types. Each time you call this the program will jump to the next line so you just have to deal with the data that comes out of it.
2. Use the sheet directly
object read = sheet.Read("B8"); read = sheet.Read("B", 8); read = sheet.Read(8, 2);
These 3 methods return the same thing, note that the third call is using the more common order of arguments where row is first (looks reversed from the first 2 methods).
Mapping with BufferedExcelReader
1. The Model
The model is just a class with properties, the only difference is we must define the Mapping attribute on each property to identify the column that will contain the data.
public class ReceiptLine { [Mapping("A")] public string Store { get; set; } [Mapping("B")] public string Invoice { get; set; } [Mapping("C")] public string Date { get; set; } }
You can see that the argument for the Mapping attribute is the column that the data will be pulled from.
2. The Mappable Object
Now we want to populate a collection of ReceiptLines from an excel file, this is trivial:
BufferedExcelReader reader = new BufferedExcelReader(fileName); BufferedExcelMap bufferedExcelMap = reader.SelectedSheet.GetMap(9); List receiptLines = bufferedExcelMap.CreateClasses();
public IEnumerable GetReceiptLines(string fileName) { BufferedExcelReader reader = new BufferedExcelReader(fileName); BufferedExcelReader.Sheet sheet = reader.Sheets.First(s => s.Name == "Invoice Summary"); BufferedExcelMap bufferedExcelMap = sheet.GetMap(7); List fleetLines = bufferedExcelMap.CreateClasses(); return fleetLines; }
Performance