Simplexcel

Note: This documentation is for Version 1.0.5, targeting .net Framework 4.
For newer Versions (targeting .NET Standard 1.3/.NET Core and .NET Framework 4.5+), see https://github.com/mstum/Simplexcel/


Table of Contents

1. Overview
1.1. About
2. Examples
2.1. Creating a Workbook
2.2. Cell creation
2.3. Cell formatting
2.4. Page Setup
2.5. Hyperlinks
2.6. Polish & Misc.
2.7. Caveats and Exceptions
3. ActionResult for ASP.net MVC
4. Version History
5. License

Chapter 1. Overview

1.1. About

Simplexcel is a simple library to generate Excel 2007+ workbooks in their native .xlsx format without relying on COM interop or other mechanisms unsuitable for server use.

PM> Install-Package simplexcel

Chapter 2. Examples

2.1. Creating a Workbook

The simple example of creating a workbook only requires you to create a few Worksheets, populate their Cells, and add them to a new Workbook.

// using Simplexcel;
var sheet = new Worksheet("Hello, world!");
sheet.Cells[0, 0] = "Hello,";
sheet.Cells["B1"] = "World!";

var workbook = new Workbook();
workbook.Add(sheet);
workbook.Save(@"d:\test.xlsx");
		

2.2. Cell creation

Cells can be created implicitly from strings, int64's, double and decimal (and anything that's implicitly convertible to those, e.g. int32), or explicitly through the Cell constructor.

Cell textCell = "fromString";
Cell intCell = 4; // will be formatted as number without decimal places "0"
Cell doubleCell = 123.456; // will be formatted with 2 decimal places, "0.00"
Cell decimalCell = 987.654321m; // will be formatted with 2 decimal places, "0.00"
decimalCell.Format = "0.000"; // override the cell format with an Excel Formatting string

// Explicit constructor, specifying the type, value and format (Excel will display this as 88.75%)
Cell decimalWithFormat = new Cell(CellType.Number, 0.8875m, BuiltInCellFormat.PercentTwoDecimalPlaces);
			

2.3. Cell formatting

After you've added a cell, you can set formatting like Bold or Font Size or Border on it.

// Addressing cells via zero-based row and column index...
sheet.Cells[0, 0] = "Hello,";
sheet.Cells[0, 0].Bold = true;
// ...or Excel-style references, B1 = [0,1]
sheet.Cells["B1"] = "World!";
sheet.Cells["B1"].Border = CellBorder.Bottom | CellBorder.Right;

Cell myCell = "Test Cell";
myCell.FontName = "Comic Sans MS";
myCell.FontSize = 18;
myCell.TextColor = System.Drawing.Color.Violet;
myCell.Bold = true;
myCell.Italic = true;
myCell.Underline = true;
myCell.Border = CellBorder.All; // Left | Right | Top | Bottom
sheet.Cells[0, 2] = myCell;

// To change the width of a column, specify a value. Specifying NULL will use the default
sheet.ColumnWidths[2] = 30;
			

In Excel, this will create a beautiful sheet:

2.4. Page Setup

A Worksheet has a PageSetup property that contains the orientation (portrait or landscape) and a setting to repeat a number of rows or columns (starting from the top and left respectively) on every page when printing.

var sheet = new Worksheet("Hello, world!");
sheet.PageSetup.PrintRepeatRows = 2; // How many rows (starting with the top one)
sheet.PageSetup.PrintRepeatColumns = 0; // How many columns (starting with the left one, 0 is default)
sheet.PageSetup.Orientation = Orientation.Landscape;


sheet.Cells["A1"] = "Title!";
sheet.Cells["A1"].Bold = true;
sheet.Cells["A2"] = "Subtitle!";
sheet.Cells["A2"].Bold = true;
sheet.Cells["A2"].TextColor = System.Drawing.Color.Magenta;
for (int i = 0; i < 100; i++)
{
    sheet.Cells[i + 2, 0] = "Entry Number " + (i + 1);
}
			

This looks like this when printing:

2.5. Hyperlinks

You can create Hyperlinks for a cell.

 sheet.Cells["A1"] = "Click me now!";  
 sheet.Cells["A1"].Hyperlink = "http://mstum.github.io/Simplexcel/";  
      

This will NOT automatically format it as a Hyperlink (blue/underlined) to give you freedom to format as desired.

2.6. Polish & Misc.

You can specify a Compression level. By default, a balance between size and performance is chosen.

workbook.Save(@"d:\testNoComp.xlsx", CompressionLevel.NoCompression);
workbook.Save(@"d:\testDefault.xlsx", CompressionLevel.Balanced); // default for Save(string)
workbook.Save(@"d:\testMaxComp.xlsx", CompressionLevel.Maximum);
			

You can also save to a Stream. The Stream must be writable.

workbook.Save(HttpContext.Current.Response.OutputStream, CompressionLevel.Maximum);
			

The workbook class allows you to add an Author and Title, which will show up in the Properties pane.

var workbook = new Workbook();
workbook.Title = "Hello, World!";
workbook.Author = "My Application Version 1.0.0.5";
			

To help troubleshooting issues with generated xlsx files, they contain a file called simplexcel.xml which contains version information and the date the document was generated.

<docInfo xmlns="http://stum.de/simplexcel/v1">
	<version major="1" minor="0" build="2" revision="0"></version>
	<created>2012-09-07T21:04:18.5220876Z</created>
</docInfo>				
			

2.7. Caveats and Exceptions

Here's a list of things to be aware of when working with Simplexcel

// Sheet names cannot be NULL or empty
new Worksheet(null); // ArgumentException
new Worksheet(""); // ArgumentException

// Sheet names cannot be longer than 31 chars
new Worksheet(new string('a', 32));  // ArgumentException

// Sheet names cannot contain these chars: \ / ? * [ ]
new Worksheet("Data for 09/22/2012"); // ArgumentException

// There are static properties on the Worksheet class to help you create valid names
int maxLength = Worksheet.MaxSheetNameLength;
char[] invalidChars = Worksheet.InvalidSheetNameChars;

// Within a workbook, sheet names must be unique
var wb = new Workbook();
var sheet1 = new Worksheet("Hello!");
var sheet2 = new Worksheet("Hello!");
wb.Add(sheet1);
wb.Add(sheet2); // ArgumentException

// Accessing a cell before it's been assigned returns NULL
sheet1.Cells["A1"].Bold = true; // NullReferenceException	

Chapter 3. ActionResult for ASP.net MVC

If you want to generate Excel Sheets as part of an ASP.net MVC action, you can use this abstract class as an ActionResult. A derived class would simply override GenerateWorkbook. This assumes that the controller merely creates a model, and that the actual workbook generation happens after the action is executed and ActionResult.ExecuteResult is called. Alternatively, you can change it to take a Workbook in the constructor and create the Workbook in the MVC Controller Action.

public abstract class ExcelResultBase : ActionResult
{
	private readonly string _filename;

	protected ExcelResultBase(string filename)
	{
		_filename = filename;
	}

	protected abstract Workbook GenerateWorkbook();

	public override void ExecuteResult(ControllerContext context)
	{
		if (context == null)
		{
			throw new ArgumentNullException("context");
		}

		var workbook = GenerateWorkbook();
		if (workbook == null)
		{
			context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
			return;
		}

		context.HttpContext.Response.ContentType = "application/octet-stream";
		context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
		context.HttpContext.Response.AppendHeader("content-disposition", "attachment; filename=\"" + _filename + "\"");
		workbook.Save(context.HttpContext.Response.OutputStream, CompressionLevel.NoCompression);
	}
}
		

Chapter 4. Version History

Version 1.0.3 (2013-08-20)

  • Added support for external hyperlinks

  • Made Workbooks serializable using the .net DataContractSerializer

Version 1.0.2 (2013-01-10)

  • Initial public release.

Chapter 5. License

The MIT License (MIT)

Copyright (c) 2013 Michael Stum, http://www.Stum.de opensource@stum.de

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.