All Projects → mganss → Excelmapper

mganss / Excelmapper

Licence: mit
Map POCO objects to Excel files

Projects that are alternatives of or similar to Excelmapper

Npoi.mapper
Use this tool to import or export data with Excel file. The tool is a convention based mapper between strong typed object and Excel data via NPOI.
Stars: ✭ 348 (+109.64%)
Mutual labels:  excel, xlsx, xls, orm, mapper
Docjure
Read and write Office documents from Clojure
Stars: ✭ 510 (+207.23%)
Mutual labels:  excel, xlsx, xls
Easyexcel
快速、简单避免OOM的java处理Excel工具
Stars: ✭ 22,133 (+13233.13%)
Mutual labels:  excel, xlsx, xls
Phpspreadsheet
A pure PHP library for reading and writing spreadsheet files
Stars: ✭ 10,627 (+6301.81%)
Mutual labels:  excel, xlsx, xls
Xresloader
跨平台Excel导表工具(Excel=>protobuf/msgpack/lua/javascript/json/xml)
Stars: ✭ 161 (-3.01%)
Mutual labels:  excel, xlsx, xls
J
❌ Multi-format spreadsheet CLI (now merged in http://github.com/sheetjs/js-xlsx )
Stars: ✭ 343 (+106.63%)
Mutual labels:  excel, xlsx, xls
Sheetjs
📗 SheetJS Community Edition -- Spreadsheet Data Toolkit
Stars: ✭ 28,479 (+17056.02%)
Mutual labels:  excel, xlsx, xls
spreadsheet
Yii2 extension for export to Excel
Stars: ✭ 79 (-52.41%)
Mutual labels:  excel, xlsx, xls
Tableexport
The simple, easy-to-implement library to export HTML tables to xlsx, xls, csv, and txt files.
Stars: ✭ 781 (+370.48%)
Mutual labels:  excel, xlsx, xls
Pyexcel
Single API for reading, manipulating and writing data in csv, ods, xls, xlsx and xlsm files
Stars: ✭ 902 (+443.37%)
Mutual labels:  excel, xlsx, xls
Desktopeditors
An office suite that combines text, spreadsheet and presentation editors allowing to create, view and edit local documents
Stars: ✭ 1,008 (+507.23%)
Mutual labels:  excel, xlsx, xls
dbd
dbd is a database prototyping tool that enables data analysts and engineers to quickly load and transform data in SQL databases.
Stars: ✭ 30 (-81.93%)
Mutual labels:  excel, xlsx, xls
exoffice
Library to parse common excel formats (xls, xlsx, csv)
Stars: ✭ 31 (-81.33%)
Mutual labels:  excel, xlsx, xls
Myexcel
MyExcel, a new way to operate excel!
Stars: ✭ 1,198 (+621.69%)
Mutual labels:  excel, xlsx, xls
spark-hadoopoffice-ds
A Spark datasource for the HadoopOffice library
Stars: ✭ 36 (-78.31%)
Mutual labels:  excel, xlsx, xls
Readxl
Read excel files (.xls and .xlsx) into R 🖇
Stars: ✭ 585 (+252.41%)
Mutual labels:  excel, xlsx, xls
xltpl
A python module to generate xls/x files from a xls/x template.
Stars: ✭ 46 (-72.29%)
Mutual labels:  excel, xlsx, xls
eec
A fast and lower memory excel write/read tool.一个非POI底层,支持流式处理的高效且超低内存的Excel读写工具
Stars: ✭ 93 (-43.98%)
Mutual labels:  excel, xlsx, xls
Rows
A common, beautiful interface to tabular data, no matter the format
Stars: ✭ 739 (+345.18%)
Mutual labels:  excel, xlsx, xls
Documentbuilder
ONLYOFFICE Document Builder is powerful text, spreadsheet, presentation and PDF generating tool
Stars: ✭ 61 (-63.25%)
Mutual labels:  excel, xlsx, xls

ExcelMapper

NuGet version Build status codecov.io netstandard2.0 net461

A library to map POCO objects to Excel files.

Features

  • Read and write Excel files
  • Uses the pure managed NPOI library instead of the Jet database engine (NPOI users group)
  • Map to Excel files using header rows (column names) or column indexes (no header row)
  • Optionally skip blank lines when reading
  • Preserve formatting when saving back files
  • Optionally let the mapper track objects
  • Map columns to properties through convention, attributes or method calls
  • Use custom or builtin data formats for numeric and DateTime columns
  • Map formulas or formula results depending on property type
  • Map JSON
  • Fetch/Save dynamic objects
  • Use records

Read objects from an Excel file

var products = new ExcelMapper("products.xlsx").Fetch<Product>();

This expects the Excel file to contain a header row with the column names. Objects are read from the first worksheet. If the column names equal the property names (ignoring case) no other configuration is necessary. The format of the Excel file (xlsx or xls) is autodetected.

Map to specific column names

public class Product
{
  public string Name { get; set; }
  [Column("Number")]
  public int NumberInStock { get; set; }
  public decimal Price { get; set; }
}

This maps the column named Number to the NumberInStock property.

Map to column indexes

public class Product
{
    [Column(1)]
    public string Name { get; set; }
    [Column(Letter="C")]
    public int NumberInStock { get; set; }
    [Column(4)]
    public decimal Price { get; set; }
}

var products = new ExcelMapper("products.xlsx") { HeaderRow = false }.Fetch<Product>();

Note that column indexes don't need to be consecutive. When mapping to column indexes, every property needs to be explicitly mapped through the ColumnAttribute attribute or the AddMapping() method. You can combine column indexes with column names to specify an explicit column order while still using a header row.

Map through method calls

var excel = new ExcelMapper("products.xls");
excel.AddMapping<Product>("Number", p => p.NumberInStock);
excel.AddMapping<Product>(1, p => p.NumberInStock);
excel.AddMapping(typeof(Product), "Number", "NumberInStock");
excel.AddMapping(typeof(Product), ExcelMapper.LetterToIndex("A"), "NumberInStock");

Multiple mappings

You can map a single column to multiple properties but you need to be aware of what should happen when mapping back from objects to Excel. To specify the single property you want to map back to Excel, add MappingDirections.ExcelToObject in the Column attribute of all other properties that map to the same column. Alternatively, you can use the FromExcelOnly() method when mapping through method calls.

public class Product
{
    public decimal Price { get; set; }
    [Column("Price", MappingDirections.ExcelToObject)]
    public string PriceString { get; set; }
}

// or

excel.AddMapping<Product>("Price", p => p.PriceString).FromExcelOnly();

Dynamic mapping

You don't have to specify a mapping to static types, you can also fetch a collection of dynamic objects.

var products = new ExcelMapper("products.xlsx").Fetch(); // -> IEnumerable<dynamic>
products.First().Price += 1.0;

The returned dynamic objects are instances of ExpandoObject with an extra property called __indexes__ that is a dictionary specifying the mapping from property names to column indexes. If you set the HeaderRow property to false on the ExcelMapper object, the property names of the returned dynamic objects will match the Excel "letter" column names, i.e. "A" for column 1 etc.

Save objects

var products = new List<Product>
{
    new Product { Name = "Nudossi", NumberInStock = 60, Price = 1.99m },
    new Product { Name = "Halloren", NumberInStock = 33, Price = 2.99m },
    new Product { Name = "Filinchen", NumberInStock = 100, Price = 0.99m },
};

new ExcelMapper().Save("products.xlsx", products, "Products");

This saves to the worksheet named "Products". If you save objects after having previously read from an Excel file using the same instance of ExcelMapper the style of the workbook is preserved allowing use cases where an Excel template is filled with computed data.

Track objects

var products = new ExcelMapper("products.xlsx").Fetch<Product>().ToList();
products[1].Price += 1.0m;
excel.Save("products.out.xlsx");

Ignore properties

public class Product
{
    public string Name { get; set; }
    [Ignore]
    public int Number { get; set; }
    public decimal Price { get; set; }
}

// or

var excel = new ExcelMapper("products.xlsx");
excel.Ignore<Product>(p => p.Price);

Use specific data formats

public class Product
{
    [DataFormat(0xf)]
    public DateTime Date { get; set; }

    [DataFormat("0%")]
    public decimal Number { get; set; }
}

You can use both builtin formats and custom formats. The default format for DateTime cells is 0x16 ("m/d/yy h:mm").

Map formulas or results

Formula columns are mapped according to the type of the property they are mapped to: for string properties, the formula itself (e.g. "=A1+B1") is mapped, for other property types the formula result is mapped. If you need the formula result in a string property, use the FormulaResult attribute.

public class Product
{
    [FormulaResult]
    public string Result { get; set; }
}

// or

excel.AddMapping<Product>("Result" p => p.Result).AsFormulaResult();

Custom mapping

If you have specific requirements for mapping between cells and objects, you can use custom conversion methods. Here, cells that contain the string "NULL" are mapped to null:

public class Product
{
    public DateTime? Date { get; set; }
}

excel.AddMapping<Product>("Date", p => p.Date)
    .SetCellUsing((c, o) =>
    {
        if (o == null) c.SetCellValue("NULL"); else c.SetCellValue((DateTime)o);
    })
    .SetPropertyUsing(v =>
    {
        if ((v as string) == "NULL") return null;
        return Convert.ChangeType(v, typeof(DateTime), CultureInfo.InvariantCulture);
    });

Header row and data row range

You can specify the row number of the header row using the property HeaderRowNumber (default is 0). The range of rows that are considered rows that may contain data can be specified using the properties MinRowNumber (default is 0) and MaxRowNumber (default is int.MaxValue). The header row doesn't have to fall within this range, e.g. you can have the header row in row 5 and the data in rows 10-20.

JSON

You can easily serialize to and from JSON formatted cells by specifying the Json attribute or AsJson() method.

public class ProductJson
{
    [Json]
    public Product Product { get; set; }
}

// or

var excel = new ExcelMapper("products.xls");
excel.AddMapping<ProductJson>("Product", p => p.Product).AsJson();

This also works with lists.

public class ProductJson
{
    [Json]
    public List<Product> Products { get; set; }
}

Name normalization

If the header cell values are not uniform, perhaps because they contain varying amounts of whitespace, you can specify a normalization function that will be applied to header cell values before mapping to property names. This can be done globally or for specific classes only.

excel.NormalizeUsing(n => Regex.Replace(n, "\w", ""));

This removes all whitespace so that columns with the string " First Name " map to a property named FirstName.

Records

Records are supported. If the type has no default constructor (as is the case for positional records) the constructor with the highest number of arguments is used to initialize objects. This constructor must have a parameter for each of the mapped properties with the same name as the corresponding property (ignoring case). The remanining parameters will receive the default value of their type.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].