A project: from CSV to Excel
A real program uses several packages together. This project reads sales from a CSV text with CsvHelper, keeps the rows in a LiteDB database, finds some of them with a query, adds up the amounts by region, and writes an Excel report with ClosedXML. It brings the lessons on packages together in one program.
What you will learn#
- using three packages from one project file and one
dotnet publish, - wrapping each DLL into its own folder and loading the classes,
- reading a CSV with CsvHelper (the header, and fields by the name of their column),
- keeping rows as documents in LiteDB and finding rows with a query,
- turning the answers into an Excel file with ClosedXML, and reading it back to check it.
The plan#
The program has one job, and each package does one part of it:
| Step | Package | What happens |
|---|---|---|
| 1 | CsvHelper | the CSV text is read row by row, and a field is taken by the name of its column |
| 2 | LiteDB | each row is stored as a document in a collection (a file on disk) |
| 3 | LiteDB | a query finds the rows with 9 units or more |
| 4 | Ring | the amounts are added up for each region |
| 5 | ClosedXML | a workbook with two sheets is written: all rows with a formula for the amount, and the totals |
| 6 | ClosedXML | the file is read back, and the total that the formula gives is checked |
Ring does the adding in step 4 itself, because it is one loop. The point is to see the three packages working together.
One project for three packages#
The packages of the earlier lessons each had a project file of their own. Here one project file names all three, and one dotnet publish copies them with everything they need:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<AssemblyName>Report</AssemblyName>
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="33.0.1" />
<PackageReference Include="LiteDB" Version="5.0.21" />
<PackageReference Include="ClosedXML" Version="0.104.2" />
</ItemGroup>
</Project>wrapassembly.ring then runs once for each DLL, with a folder for each (Report/classes/CsvHelper, .../LiteDB, .../ClosedXML), and each run names the namespace that the program uses. A folder of its own for each assembly keeps the generated files of the three apart.
The program#
# a project with three packages - CsvHelper reads a CSV text, LiteDB stores the rows and finds some of them, ClosedXML writes an Excel report
# (the project is in the folder Report: Report.csproj names the three packages, and Empty.cs is the one source file a project needs)
load "dotnet.ring"
using { "System.IO" "System.Globalization" }
cHere = currentdir()
cLibs = cHere + "/Report/libs/"
cClasses = cHere + "/Report/classes/"
# STEP 1. Get the packages (nuget.org the first time) with dotnet publish: one folder with the three DLLs and the DLLs they need
if not fexists(cLibs + "CsvHelper.dll")
? "getting the packages..."
system("dotnet publish Report -c Release -o Report/libs -nologo -v q > nul")
ok
if not fexists(cLibs + "CsvHelper.dll")
? "The packages could not be restored. They are downloaded from nuget.org the first time, so the computer needs the internet once."
bye
ok
# STEP 2. Make Ring classes: one folder for each DLL (the namespaces that the program uses)
chdir("../../../tools/dotnettools")
system(exefilename() + " wrapassembly.ring " + cLibs + "CsvHelper.dll " + cClasses + "CsvHelper CsvHelper > nul")
system(exefilename() + " wrapassembly.ring " + cLibs + "LiteDB.dll " + cClasses + "LiteDB LiteDB > nul")
system(exefilename() + " wrapassembly.ring " + cLibs + "ClosedXML.dll " + cClasses + "ClosedXML ClosedXML.Excel > nul")
chdir(cHere)
# STEP 3. Load the three assemblies and their classes
dnLoad(cLibs + "CsvHelper.dll")
dnImportFrom(cClasses + "CsvHelper/","CsvHelper")
dnLoad(cLibs + "LiteDB.dll")
dnImportFrom(cClasses + "LiteDB/","LiteDB")
dnLoad(cLibs + "ClosedXML.dll")
dnImportFrom(cClasses + "ClosedXML/","ClosedXML.Excel")
func main
cTemp = new Path().GetTempPath()
cDbFile = new Path().Combine([cTemp,"ringdotnet-sales.db"])
cXlsx = new Path().Combine([cTemp,"ringdotnet-sales-report.xlsx"])
if new File().Exists(cDbFile) new File().Delete(cDbFile) ok
# 1. The data: a CSV text (a program would read a file: new StreamReader for a path)
cCsv = "date,region,product,units,price" + nl
cCsv += "2024-03-01,North,Tea,10,2.5" + nl
cCsv += "2024-03-01,North,Cake,4,8" + nl
cCsv += "2024-03-02,South,Tea,7,2.5" + nl
cCsv += "2024-03-02,South,Coffee,12,3" + nl
cCsv += "2024-03-03,East,Cake,6,8" + nl
cCsv += "2024-03-03,East,Tea,3,2.5" + nl
cCsv += "2024-03-04,North,Coffee,9,3" + nl
cCsv += "2024-03-04,South,Cake,2,8" + nl
# 2. CsvHelper reads it: ReadHeader takes the first line, and Read goes to the next row. A field is read by the name of its column.
oText = new StringReader(cCsv)
oCulture = new CultureInfo("en-US")
oCsv = (new CsvReader).@New([ :reader = oText, :culture = oCulture ])
oCsv.Read()
oCsv.ReadHeader()
# 3. LiteDB keeps each row as a document. The database is a file, the collection is like a table.
oDb = new LiteDatabase(cDbFile)
oSales = oDb.GetCollection([ :name = "sales" ])
nRows = 0
while oCsv.Read()
oDoc = new BsonDocument()
oDoc.Add([ :key = "date", :value = oCsv.GetField("date") ])
oDoc.Add([ :key = "region", :value = oCsv.GetField("region") ])
oDoc.Add([ :key = "product", :value = oCsv.GetField("product") ])
oDoc.Add([ :key = "units", :value = number(oCsv.GetField("units")) ])
oDoc.Add([ :key = "price", :value = number(oCsv.GetField("price")) ])
oSales.Insert(oDoc)
nRows++
end
oText.Dispose()
? "1. rows read from the CSV and stored: " + nRows + ", in the database: " + oSales.callMethod("Count",[])
# 4. A query: the rows with 9 units or more. The condition is a text in the query language of LiteDB.
oBig = oSales.Find(new BsonExpression().Create("$.units >= 9"))
aBig = []
aRows = oBig.toList()
for oRow in aRows
aBig + [oRow.Item("region").AsString,oRow.Item("product").AsString,oRow.Item("units").AsInt32]
next
aBig = sort(aBig,1)
? "2. rows with 9 units or more:"
for aRow in aBig
? " " + aRow[1] + " " + aRow[2] + " " + aRow[3]
next
# 5. Totals by region: the rows come out of the database as documents and Ring adds them up
aTotals = [] # [region, amount]
aAll = []
aRows = oSales.FindAll().toList()
for oRow in aRows
cRegion = oRow.Item("region").AsString
nAmount = oRow.Item("units").AsInt32 * oRow.Item("price").AsDouble
nPos = find(aTotals,cRegion,1)
if nPos = 0
aTotals + [cRegion,0]
nPos = len(aTotals)
ok
aTotals[nPos][2] += nAmount
aAll + [oRow.Item("date").AsString,cRegion,oRow.Item("product").AsString,oRow.Item("units").AsInt32,oRow.Item("price").AsDouble]
next
aTotals = sort(aTotals,1)
aAll = sort(aAll,1)
? "3. total by region:"
for aTotal in aTotals
? " " + aTotal[1] + " " + aTotal[2]
next
oDb.Dispose()
# 6. ClosedXML writes the report: a sheet with all the rows (the amount is a formula) and a sheet with the totals
oBook = new XLWorkbook()
oSheet = oBook.AddWorksheet("Sales")
aHeader = ["Date","Region","Product","Units","Price","Amount"]
for nColumn = 1 to len(aHeader)
oSheet.Cell(char(64 + nColumn) + "1").Value = aHeader[nColumn]
next
oSheet.Range("A1:F1").Style.Font.Bold = true
for nLine = 1 to len(aAll)
nRow = nLine + 1
for nColumn = 1 to 5
oSheet.Cell(char(64 + nColumn) + nRow).Value = aAll[nLine][nColumn]
next
oSheet.Cell("F" + nRow).FormulaA1 = "=D" + nRow + "*E" + nRow
next
nLast = len(aAll) + 1
oSheet.Cell("E" + (nLast + 1)).Value = "Total"
oSheet.Cell("F" + (nLast + 1)).FormulaA1 = "=SUM(F2:F" + nLast + ")"
oBy = oBook.AddWorksheet("By region")
oBy.Cell("A1").Value = "Region"
oBy.Cell("B1").Value = "Amount"
oBy.Range("A1:B1").Style.Font.Bold = true
for nLine = 1 to len(aTotals)
oBy.Cell("A" + (nLine + 1)).Value = aTotals[nLine][1]
oBy.Cell("B" + (nLine + 1)).Value = aTotals[nLine][2]
next
oBook.SaveAs(cXlsx)
oBook.Dispose()
# 7. Read the report back: the formulas are worked out when the cells are read
oRead = new XLWorkbook().@New([ :file = cXlsx ])
oBack = oRead.Worksheet("Sales")
? nl + "4. the report has the sheets Sales and By region, and " + (oBack.LastRowUsed(NULL).RowNumber() - 2) + " rows of sales and a total row"
? " the total of the sheet Sales (a formula): " + oBack.Cell("F" + (nLast + 1)).Value.GetNumber()
oRead.Dispose()
new File().Delete(cXlsx)
if new File().Exists(cDbFile) new File().Delete(cDbFile) ok1. rows read from the CSV and stored: 8, in the database: 8
2. rows with 9 units or more:
North Tea 10
North Coffee 9
South Coffee 12
3. total by region:
East 55.50
North 84
South 69.50
4. the report has the sheets Sales and By region, and 8 rows of sales and a total row
the total of the sheet Sales (a formula): 209The totals can be checked by hand: East is 6 × 8 + 3 × 2.5 = 55.5, North is 10 × 2.5 + 4 × 8 + 9 × 3 = 84, South is 7 × 2.5 + 12 × 3 + 2 × 8 = 69.5, and together they are 209, which is also what the formula in the report gives.
How it works#
Reading the CSV#
CsvReader takes a reader of text and a culture, which tells it how numbers are written (en-US has a decimal point). The text comes from a Ring text here, through a StringReader; for a file you would give a StreamReader of its path. Read() moves to the next row, and the first Read() followed by ReadHeader() takes the names of the columns, so that GetField("units") finds a field by the name of its column and not by its position. A field comes back as a text; number(...) makes the numbers of it.
Keeping the rows in LiteDB#
LiteDB is a small database in one file, and it keeps documents: a document is a set of named values, like a Ring list of pairs. new BsonDocument() is a document, and Add([ :key = ..., :value = ... ]) puts a value in it (the overload is chosen by the names of the parameters). A collection is where documents are kept, like a table. Its type is generic, so it has no Ring class of its own and its methods are called with callMethod: Insert, Count, Find and FindAll.
Asking a question#
Find takes a condition written as a text in the language of LiteDB: "$.units >= 9" says "the field units of the document is 9 or more". The condition is made with new BsonExpression().Create(...). The answer is a collection of documents, and toList() copies it into a Ring list. A value of a document is read with the method that matches its type: AsString, AsInt32 or AsDouble.
Adding up#
LiteDB has its own functions for sums, and the program uses a short loop instead: it keeps a list of [region, amount] pairs, finds the region with find(aTotals,cRegion,1) and adds the amount of the row. The lists are then sorted so that the output and the report always come in the same order.
Writing the report#
The workbook has two sheets: Sales has one row for each sale, and the amount of each row is a formula (=D2*E2) that Excel works out; the last row has the sum of the column. By region has the totals that Ring added up. The header cells are bold. The steps are those of the lesson Excel files.
Reading the report back#
A formula has no stored value until something works it out. When the program reads the file back, ClosedXML works out the formula of the total cell, so GetNumber() gives 209. That is a simple check that the report is right.
What you learned#
- three packages can share one project file and one publish, each wrapped into its own folder,
- CsvHelper reads rows and fields by the names of the columns,
- LiteDB keeps documents, finds them with a query, and its collections are used with
callMethod, - ClosedXML writes sheets with formulas, and reading the file back checks the report,
- each package does one job, and Ring joins the jobs.
Exercises#
- Add two more rows to the CSV text and see how the totals and the report change.
- Change the query to
$.region = 'South' AND $.units >= 5and print the rows that it finds. - Read the CSV from a file: write the text to a file, open it with
dnNew("System.IO.StreamReader",[ :path = cFile ])and give that reader toCsvReader. - Add a third sheet By product with the amount of each product, in the same way as the sheet By region.