Reading and writing Excel (xlsx), OpenDocument (ods) and CSV spreadsheets: sheets, cells, styles, formulas and dates.
import excel
A workbook holds several sheets, and each sheet holds cells by row and column, from zero. Turn Excel references such as C5 into a row and column with CellRef and ParseCellRef.
Open and Save work the format out from the file extension. Formulas are stored and read with their last calculated result, but Salam does not evaluate a formula itself.
Use it when people hand you spreadsheets or expect one back: an upload form for price lists, a monthly report for the finance team, an export button. When the data is only ever read by programs, a CSV file with encoding.csv is simpler; for analysis on columns of numbers, load the rows into a table with data.
What trips people up
•
Old .xls files are read. BIFF8 workbooks (Excel 97 to 2003), including OLE2 streams stored in the mini stream, are decoded into sheets, strings, numbers, booleans, dates, errors, merged cells and cached formula values. Save still writes xlsx, ods or csv only.
•
The extension decides the format.DetectFormat, Open and Save look only at the file name, so an xlsx saved as report.dat will not open. Rename uploads, or check the first bytes (PK for xlsx and ods) yourself.
•
Formulas are not evaluated. A formula cell carries the result stored with it; when you write one, compute and pass the result yourself.
•
Rows and columns count from zero, while Excel shows 1 and A. ParseCellRef and CellRef convert.
•
SheetToJSON gives strings only: an array of rows, each an array of the cells' text. Read Cell.kind when you need the numbers.
The guide below covers the jobs that come up in real programs: reading a sheet someone else filled in, building a formatted report, working with dates, turning a workbook into CSV files, and finding values by reference or by content.
Reading rows from a sheet someone else filled in
A spreadsheet that people edit by hand is never quite regular: columns move, rows are left empty, a number cell holds a word. Find each column by its header text instead of trusting its position, skip rows with no key, and look at Cell.kind before you treat a value as a number. get_string always gives text, whatever the cell holds, so it is safe for messages. Open reports a file it cannot read through ok and err.
excel-read-rows.salam
import excel
funcheader_col(sheet: excel.Sheet*, name: str): int:
repeat sheet.col_count() in c:
if sheet.get_string(0, c) == name: ret c endendret -1endfuncmake_file():
mut book := excel.NewWorkbook()
s := book.add_sheet("grades")
each c, title in ["Name", "City", "Score"]: s.set_string(0, c, title) end
s.set_string(1, 0, "Ali")
s.set_string(1, 1, "Tehran")
s.set_number(1, 2, 17.5)
s.set_string(2, 0, "Sara")
s.set_string(2, 1, "Shiraz")
s.set_number(2, 2, 19)
s.set_string(4, 0, "Reza")
s.set_string(4, 2, "absent")
book.save("grades.xlsx")
book.Free()
endfuncmain:
make_file()
mut ok := falsemut err := ""mut book := excel.Open("grades.xlsx", ok, err)
if ok == false:
println"cannot open:", err
ret1end
sheet := book.sheet_at(0)
name_col := header_col(sheet, "Name")
score_col := header_col(sheet, "Score")
mut total := 0.0mut counted := 0repeat sheet.row_count() - 1in i:
r := i + 1if sheet.has_cell(r, name_col) == false: continueend
cell := sheet.get_cell(r, score_col)
if cell.kind != excel.CellNumber:
println sheet.get_string(r, name_col), "skipped:", sheet.get_string(r, score_col)
continueendprintln sheet.get_string(r, name_col), cell.num
total += cell.num
counted++
endprintln"average of", counted, "=", total / (counted asf64)
book.Free()
ret0end
Output
Ali 17.5
Sara 19
Reza skipped: absent
average of 2 = 18.25
Rows count from zero, so the header is row 0 and data starts at row 1. row_count is one past the last row that has a cell, which is why the empty row 3 still appears in the loop and is skipped by has_cell.
Building a formatted report
A Style describes bold text, font size, background colour, alignment and number format. Register each style once with book.styles.get_or_add, which returns an id, and give that id to set_style for as many cells as you like. merge_cells joins a range for a title, and set_formula stores a formula together with the value you computed, because Salam writes formulas but does not evaluate them.
excel-report.salam
import excel
funcmain:
mut book := excel.NewWorkbook()
mut sheet := book.add_sheet("March")
title := book.styles.GetOrAdd(
excel.Style { bold = true, font_size = 14, align_h = excel.AlignCenter }
)
head := book.styles.GetOrAdd(excel.Style { bold = true, bg_color = "DDEBF7" })
money := book.styles.GetOrAdd(excel.Style { num_format = "#,##0.00" })
sheet.set_string(0, 0, "Sales, March 2026")
sheet.merge_cells(0, 0, 0, 3)
sheet.set_style(0, 0, title)
each col, name in ["Item", "Qty", "Price", "Total"]:
sheet.set_string(1, col, name)
sheet.set_style(1, col, head)
end
items := ["Tea", "Sugar", "Rice"]
qty := [12, 30, 5]
price := [4.5, 1.25, 9.8]
mut sum := 0.0repeat3in i:
r := i + 2
line := (qty[i] asf64) * price[i]
sheet.set_string(r, 0, items[i])
sheet.set_int(r, 1, qty[i] asi64)
sheet.set_number(r, 2, price[i])
sheet.set_formula(r, 3, excel.CellRef(r, 1) + "*" + excel.CellRef(r, 2), line)
sheet.set_style(r, 3, money)
sum += line
end
sheet.set_string(5, 2, "Sum")
sheet.set_formula(5, 3, "SUM(D3:D5)", sum)
sheet.set_style(5, 3, money)
println"saved:", book.save("march.xlsx")
mut ok := falsemut err := ""mut back := excel.Open("march.xlsx", ok, err)
s := back.sheet("March")
println s.get_string(0, 0), "merged:", s.is_merged(0, 3)
println s.get_formula(5, 3), "=", s.GetNumber(5, 3)
println"D3 style:", back.styles.Get(s.get_cell(2, 3).style_id).num_format
back.Free()
book.Free()
ret0end
Excel recalculates the formulas when it opens the file. Programs that read the file without Excel, this package included, see the value you stored, so always pass the correct result as the last argument of set_formula.
Dates are numbers with a format
Excel stores a date as a serial number: days since 30 December 1899, with the time of day as the fraction. set_date takes Unix seconds and stores the matching serial with a date format, EpochToSerial and SerialToEpoch convert in both directions, and a cell written with set_date reads back with kind == CellDate. Because serials are plain day counts, the difference of two dates is a number of days, which is what the formula B2-B1 stores.
kind is date: true
serial number: 46101.5
start: 2026 3 20
finish: 2026 4 2
days between: 13
serial of 1970-01-01: 25569
The program prints the parts of each date with the UTC functions of time. get_string on a date cell formats it in the local time zone, so near midnight it can show a different day from the UTC value.
From a workbook to CSV files
Open reads xlsx, ods and csv files and picks the reader from the file extension, which is also what DetectFormat looks at, so a file with the wrong extension will not open. SheetToCSV writes one sheet as CSV text with commas and quotes escaped, so exporting every sheet of a workbook is a short loop over sheet_names. Going the other way, CSVToSheet turns CSV text into a sheet.
excel-export.salam
import excel
import io
funcexport_sheets(path: str): int:
mut ok := falsemut err := ""mut book := excel.Open(path, ok, err)
if ok == false:
println"cannot open", path, ":", err
ret0end
names := book.sheet_names()
each i, name in names:
out := name + ".csv"
io.WriteFile(out, excel.SheetToCSV(book.sheets.Get(i)))
println"wrote", out
end
book.Free()
ret names.Len()
endfuncmain:
mut book := excel.NewWorkbook()
mut users := book.add_sheet("users")
users.set_string(0, 0, "name")
users.set_string(0, 1, "note")
users.set_string(1, 0, "Ali")
users.set_string(1, 1, "likes tea, not coffee")
mut stock := book.add_sheet("stock")
stock.set_string(0, 0, "item")
stock.set_string(0, 1, "count")
stock.set_string(1, 0, "pen")
stock.set_int(1, 1, 40)
excel.WriteODS(book, "office.ods")
println"format is ods:", excel.DetectFormat("office.ods") == excel.FormatODS
println"sheets exported:", export_sheets("office.ods")
println io.ReadFile("users.csv")
println io.ReadFile("stock.csv")
println"sheets exported:", export_sheets("nothing.xlsx")
book.Free()
ret0end
Output
format is ods: true
wrote users.csv
wrote stock.csv
sheets exported: 2
name,note
Ali,"likes tea, not coffee"
item,count
pen,40
cannot open nothing.xlsx : cannot open file: nothing.xlsx
sheets exported: 0
Finding values by reference or by content
People talk about cells as C3, programs use row and column numbers. ParseCellRef turns a reference into zero based numbers and returns false for something that is not a reference, CellRef goes back, and ColumnIndex and ColumnLabel do the same for a column alone. To search by content, filter_rows_equals returns the rows whose cell in one column has a given text and find returns every cell with that text.
excel-lookup.salam
import excel
funcvalue_at(sheet: excel.Sheet, ref: str): str:
mut row := 0mut col := 0if excel.ParseCellRef(ref, row, col) == false: ret"bad reference"endif sheet.has_cell(row, col) == false: ret"empty"endret sheet.get_string(row, col)
endfuncmain(): intthrow:
mut s := try excel.CSVToSheet(
"order,city,item\n101,Tehran,pen\n102,Tabriz,book\n103,Tehran,book\n104,Shiraz,pen\n",
"orders"
)
println"C3 =", value_at(s, "C3"), "| A9 =", value_at(s, "A9"), "| 3C =", value_at(s, "3C")
rows := s.filter_rows_equals(1, "Tehran")
each r in rows:
println"Tehran order", s.get_string(r, 0), "is a", s.get_string(r, 2)
end
hits := s.Find("book")
println"book appears", hits.Len(), "times"
city := excel.ColumnIndex("B")
println"column B holds",
s.get_column(city).Len(),
"cells, the last column is",
excel.ColumnLabel(s.col_count() - 1)
s.Free()
ret0end
Output
C3 = book | A9 = empty | 3C = bad reference
Tehran order 101 is a pen
Tehran order 103 is a book
book appears 2 times
column B holds 5 cells, the last column is C
find returns its matches in no particular order, so sort them or, as here, use only the count when the order matters.
Saves the workbook in the format the path extension names: .xlsx, .ods or .csv (for csv only the active sheet is written). Any other extension, .xls included, returns false.
Turns CSV text into a sheet; every cell is a string, blank lines stay as empty rows and quoted fields may hold line breaks. Throws the encoding.csv errors on text it cannot read.
funcReadCSVWorkbook(path: str, ok &: bool, err &: str): Workbook
Turns a CSV file into a workbook with one sheet. On a file that cannot be read ok is false and err holds the reason, with the line and column for broken CSV.