Beautify and enrich your excel documents through CSharp

Using ClosedXML.Excel as example

LAI TOCA
2 min readNov 28, 2022
Photo from: CYDA

It was common to create excel report using programming for different situations. But somehow we might decorate the content that make it more colorful and clear for reading. The story going to share the tips that we how we could deal with it (The below code snippets that generated Excel data via third-party package: ClosedXML.Excel).

Image that we have below template looks as below:

Template of beautify excel

Is’t looks a little complicated? No warry, We could separate the data sheets into three parts:

Table of header (row1/row2) without details data but warning message (row3). 
-> Table of header range - [A1:B3]
-----------------------------------------------------------------------------------------
Entire blank row (row4)
-----------------------------------------------------------------------------------------
Table of header (row5/row6) and with detail table [row7/row8~row13]
-> Table of header range - [A5:B6]
-> Table of detail range - [A7:K13]

According to above structure, we could transfer the thinking into code snippet:

ExcelHeper.cs

The key tricky here were:

  • Line(70): We converted list of data object into dictionary<string, object>, so that we could insert whole list content with header and content in Line(74).
  • We have gathered data from cell to multiples table in order to make it easily to union a section of data into same format/style and then configured diverse row separately.

Take advantage of powerful of package: ClosedXML.Excel, we have demonstrated how to apply table’s style, how to setup cell’s data type and style and conditional assignment:).

XLTableTheme.TableStyleMedium16
Custom number format of cell

Happy enjoy formatting/beautifying your own excel!!

Reference

--

--

LAI TOCA

Coding for fun. (Either you are running for food or running for being food.)