Import/export data¶
You can read and write data from and to your spreadsheet in a few different ways. The most obvious is to use the Cells property of the ExcelWorksheet class, shown on the Getting Started page. There are also a few other ways to import/export/read data from/into spreadsheets with EPPlus.
Load data into a spreadsheet¶
From the Cells property (ExcelRange) you can access these methods to load data from various sources:
LoadFromTextandLoadFromTextAsync- Read a text file (csv, tsv, etc) and load the data into a range on a worksheet.LoadFromDataReaderandLoadFromDataReaderAsync- Loads data into a range from anIDataReaderLoadFromDataTable- Loads data into a range from aSystem.Data.DataTable. Can be used for importing data from a range of sources, like XML (example provided) and databases.LoadFromCollection- Loads data into a range from anIEnumerable<T>using reflection.LoadFromCollection using attributes- Loads data into a range/table from anIEnumerable<T>using reflection. Uses attributes that specifies styling, number formats, formulas, etc.LoadFromDictionaries- Loads data into a range from anIEnumerableofExpandoObject/dynamicobjects (via theirIDictionary<string, object>interface. Useful for importing json data, example provided.LoadFromArrays- Loads data into a range from anIEnumerableofobject[]where each object array becomes a row in the worksheet.
You can optionally specify a parameter to create an ExcelTable when you use these methods. For more detailed examples, have a look at sample 4 & 5 the sample project Sample-.NET Framework or Sample-.NET Framework.
Export data from a spreadsheet¶
From the Cells property (ExcelRange) you can access these methods to write:
ToTextandToTextAsync- Writes a range to a csv string.SaveToTextandSaveToTextAsync- Writes a range to a csv file.ToDataTable- Exports data from a range to aSystem.Data.DataTableToCollection- Exports data from a range to anIEnumerable<T>where T is a class.ToJson- Exports data from a range to Json.CreateHtmlExporter- Exports data from a range to html/css.GetValue<T>- Gets a value, with the option to specify a datatypeValue- Gets or sets the value of the range.
You can also use the GetValue and SetValue methods directly on the worksheet object.
(This will give a little bit better performance than reading/writing via the range):
GetValue<T>- Gets a value of a single cell, with the option to specify a datatypeSetValue- Sets a value of a single cell
Since the Cells property implements the IEnumerable interface, you can use Linq to query data from a worksheet.
Most of these methods are demonstrated in the sample project.