Excel files
Reports, price lists and exports often come as Excel files. The ClosedXML package from nuget.org reads and writes .xlsx files without Excel on the computer. This lesson writes a small sales sheet with formulas and a bold header, reads it back, and shows what is special about a package whose classes are interfaces.
What you will learn#
- the steps of the NuGet lessons on a package that needs several DLLs,
- a workbook, a worksheet and a cell, and how to find a cell by its address,
- text, numbers and formulas in cells, and a style,
- reading a file back, including the result of a formula,
- how to call the methods of ClosedXML that have overloads.
What an .xlsx file is#
A .xlsx file is a zip file with XML inside: one part for each sheet, one for the styles, and so on. A package that knows the format can make and read these files itself, so the program does not need Excel, and it works on a server or on Linux. The package here is ClosedXML. It uses a few other packages, and dotnet publish copies all of them, as in the lesson A NuGet package.
| Part of a file | In ClosedXML | Example |
|---|---|---|
| the file | a workbook, XLWorkbook | new XLWorkbook() |
| a sheet of the file | a worksheet | oBook.AddWorksheet("Sales") |
| one square | a cell, by its address | oSheet.Cell("B2") |
| a group of squares | a range | oSheet.Range("A1:D1") |
The steps#
- A project file names the package (
Excel/Excel.csprojhere), anddotnet publish Excel -c Release -o Excel/libscopies ClosedXML and the DLLs it needs intoExcel/libs. wrapassembly.ringwrites Ring classes for the namespaceClosedXML.ExcelofClosedXML.dll. The other DLLs are not wrapped: ClosedXML uses them by itself.dnLoadanddnImportFrom.- The classes are used.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<AssemblyName>Excel</AssemblyName>
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.104.2" />
</ItemGroup>
</Project>The program#
# an Excel file with a NuGet package - ClosedXML writes and reads .xlsx files without Excel on the computer
# (the project is in the folder Excel: Excel.csproj names ClosedXML, and Empty.cs is the one source file a project needs)
load "dotnet.ring"
using { "System.IO" }
cHere = currentdir()
cDll = cHere + "/Excel/libs/ClosedXML.dll"
cClasses = cHere + "/Excel/classes"
# STEP 1. Get the package and the packages it needs (nuget.org the first time) with dotnet publish
if not fexists(cDll)
? "getting the package..."
system("dotnet publish Excel -c Release -o Excel/libs -nologo -v q > nul")
ok
if not fexists(cDll)
? "The package could not be restored. It is downloaded from nuget.org the first time, so the computer needs the internet once."
bye
ok
# STEP 2. Make Ring classes for the namespace ClosedXML.Excel of the DLL (the other DLLs in the folder are used by ClosedXML itself)
chdir("../../../tools/dotnettools")
system(exefilename() + " wrapassembly.ring " + cDll + " " + cClasses + " ClosedXML.Excel > nul")
chdir(cHere)
# STEP 3. Load the assembly and the classes
dnLoad(cDll)
dnImportFrom(cClasses + "/","ClosedXML.Excel")
func main
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet-sales.xlsx"])
# 1. A workbook is the file; a worksheet is one of its sheets; a cell is found by its address ("B2") like in Excel
oBook = new XLWorkbook()
oSheet = oBook.AddWorksheet("Sales")
aHeader = ["Product","Price","Quantity","Total"]
for nColumn = 1 to len(aHeader)
oSheet.Cell(char(64 + nColumn) + "1").Value = aHeader[nColumn]
next
oSheet.Range("A1:D1").Style.Font.Bold = true
# 2. The rows come from a Ring list. A text is a text cell, a number is a number cell, and a formula starts with =
aProducts = [ ["Tea",12.5,4], ["Coffee",20,3], ["Cake",8.25,2] ]
for nRow = 1 to len(aProducts)
nLine = nRow + 1
oSheet.Cell("A" + nLine).Value = aProducts[nRow][1]
oSheet.Cell("B" + nLine).Value = aProducts[nRow][2]
oSheet.Cell("C" + nLine).Value = aProducts[nRow][3]
oSheet.Cell("D" + nLine).FormulaA1 = "=B" + nLine + "*C" + nLine
next
oSheet.Cell("A5").Value = "All"
oSheet.Cell("D5").FormulaA1 = "=SUM(D2:D4)"
oBook.SaveAs(cFile)
oBook.Dispose()
? "1. written: " + new File().Exists(cFile)
# 3. Read it back. The formulas were worked out when the cells were read.
oRead = new XLWorkbook().@New([ :file = cFile ])
oSales = oRead.Worksheet("Sales")
nLast = oSales.LastRowUsed(NULL).RowNumber()
? "2. the sheet has " + nLast + " rows:"
for nLine = 1 to nLast
cText = oSales.Cell("A" + nLine).Value.ToString()
if nLine = 1
? " " + cText + " | Price | Quantity | Total"
else
? " " + cText + " | " + oSales.Cell("B" + nLine).Value.ToString() + " | " + oSales.Cell("C" + nLine).Value.ToString() + " | " + oSales.Cell("D" + nLine).Value.ToString()
ok
next
? "3. the total is " + oSales.Cell("D5").Value.GetNumber()
? " the header is bold: " + oSales.Cell("A1").Style.Font.Bold
oRead.Dispose()
new File().Delete(cFile)1. written: 1
2. the sheet has 5 rows:
Product | Price | Quantity | Total
Tea | 12.5 | 4 | 50
Coffee | 20 | 3 | 60
Cake | 8.25 | 2 | 16.5
All | | | 126.5
3. the total is 126.50
the header is bold: 1How it works#
Writing#
oSheet.Cell("B2").Value = 12.5 puts a number in a cell, and .Value = "Tea" puts a text. The type of the value decides the type of the cell: a number stays a number in Excel, so a formula can use it, and a text stays a text.
A formula is a text that starts with =, written to FormulaA1 (the cell address style of Excel, A1): "=B2*C2". The program builds one for each row with a Ring text ("=B" + nLine + "*C" + nLine). A formula is worked out when a value is read (by ClosedXML here, and by Excel when a person opens the file), so the program reads the file back to print the totals.
The bold header is a style: Range("A1:D1").Style.Font.Bold = true gives the whole range one setting.
Reading#
new XLWorkbook().@New([ :file = cFile ]) opens an existing file (a constructor chosen by the name of its parameter, the form of The generic functions), and Worksheet("Sales") takes a sheet by its name. LastRowUsed(NULL).RowNumber() is the number of the last row that has anything in it, so the program loops from 1 to it.
A cell holds a Value, and a value has methods: ToString() is the text of the value (also for a number or a formula), GetNumber() is the number. A cell that is empty gives an empty text, as in the last row of the output.
Ring writes a number with decimals using two decimals when it joins it to a text, so GetNumber() of 126.5 prints as 126.50 in the last line. The cell holds 126.5.
Interfaces#
ClosedXML gives you interfaces: AddWorksheet returns an IXLWorksheet, Cell returns an IXLCell, and the classes behind them are not public. The generated Ring classes are named after the interfaces (IXLWorksheet, IXLCell, IXLRange), and the objects that come back are wrapped as the right one. You never write new IXLCell: you get cells from the worksheet. An interface can inherit members from other interfaces (Font.Bold is declared in IXLFontBase), and they are all available.
Overloads#
Most of the methods of ClosedXML have several versions, and the rules of Core concepts apply:
| In C# | In Ring |
|---|---|
Cell("B2") | Cell("B2") |
Cell(2, 2) | Cell([ :row = 2, :column = 2 ]) |
LastRowUsed() | LastRowUsed(NULL) |
Worksheet("Sales") or Worksheet(1) | Worksheet("Sales") or Worksheet(1) |
The names of the parameters are in the files that the generator wrote (Excel/classes/ClosedXML.Excel.classes.ring).
Using ClosedXML in a program#
- Check the license of every package before you give a program to others. It is on the page of the package at nuget.org.
- Close what you open:
Dispose()of a workbook releases the file, so it can be moved or deleted. The program does that before it deletes the file. - Many cells are many calls. Every
Cell(...).Value = ...crosses the bridge. A sheet of a few thousand cells is fine; for hundreds of thousands, look for a method of the package that takes many values at once (ClosedXML hasInsertDatafor that).
What you learned#
- an
.xlsxfile is made and read by a package, and no Excel is needed, dotnet publishbrings a package with all its DLLs, andwrapassembly.ringcan wrap just one namespace,- cells are found by address, and hold texts, numbers and formulas,
- the classes of a package that works with interfaces,
- overloads: named parameters and
NULL.
Exercises#
- Add a fourth product, and change the sum to include its row.
- Change the total of the last row to the average price:
"=AVERAGE(B2:B4)". - Open a sheet that you made in Excel and print the text of the first column.
- Write the Ring list of a CSV file (the tutorial Tabular data) into a sheet, one cell for each field.