Standard library · Encoding and data

excel

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

func header_col(sheet: excel.Sheet*, name: str): int:
    repeat sheet.col_count() in c:
        if sheet.get_string(0, c) == name: ret c end
    end
    ret -1
end

func make_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()
end

func main:
    make_file()
    mut ok := false
    mut err := ""
    mut book := excel.Open("grades.xlsx", ok, err)
    if ok == false:
        println "cannot open:", err
        ret 1
    end
    sheet := book.sheet_at(0)
    name_col := header_col(sheet, "Name")
    score_col := header_col(sheet, "Score")
    mut total := 0.0
    mut counted := 0
    repeat sheet.row_count() - 1 in i:
        r := i + 1
        if sheet.has_cell(r, name_col) == false: continue end
        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)
            continue
        end
        println sheet.get_string(r, name_col), cell.num
        total += cell.num
        counted++
    end
    println "average of", counted, "=", total / (counted as f64)
    book.Free()
    ret 0
end
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

func main:
    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.0
    repeat 3 in i:
        r := i + 2
        line := (qty[i] as f64) * price[i]
        sheet.set_string(r, 0, items[i])
        sheet.set_int(r, 1, qty[i] as i64)
        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 := false
    mut 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()
    ret 0
end
Output
saved: true
Sales, March 2026 merged: true
SUM(D3:D5) = 140.5
D3 style: #,##0.00

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.

excel-dates.salam
import excel
import time

func show(label: str, epoch: i64):
    println label, time.YearUTC(epoch), time.MonthUTC(epoch), time.DayUTC(epoch)
end

func main:
    start := 1774008000 as i64
    finish := 1775131200 as i64
    mut book := excel.NewWorkbook()
    mut s := book.add_sheet("project")
    s.set_string(0, 0, "Start")
    s.set_date(0, 1, start)
    s.set_string(1, 0, "Finish")
    s.set_date(1, 1, finish)
    s.set_formula(2, 1, "B2-B1", excel.EpochToSerial(finish) - excel.EpochToSerial(start))
    book.save("plan.xlsx")
    mut ok := false
    mut err := ""
    mut back := excel.Open("plan.xlsx", ok, err)
    sheet := back.sheet("project")
    cell := sheet.get_cell(0, 1)
    println "kind is date:", cell.kind == excel.CellDate
    println "serial number:", cell.num
    show("start:", excel.SerialToEpoch(cell.num))
    show("finish:", excel.SerialToEpoch(sheet.GetNumber(1, 1)))
    println "days between:", sheet.GetNumber(2, 1)
    println "serial of 1970-01-01:", excel.EpochToSerial(0)
    back.Free()
    book.Free()
    ret 0
end
Output
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

func export_sheets(path: str): int:
    mut ok := false
    mut err := ""
    mut book := excel.Open(path, ok, err)
    if ok == false:
        println "cannot open", path, ":", err
        ret 0
    end
    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()
end

func main:
    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()
    ret 0
end
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

func value_at(sheet: excel.Sheet, ref: str): str:
    mut row := 0
    mut col := 0
    if excel.ParseCellRef(ref, row, col) == false: ret "bad reference" end
    if sheet.has_cell(row, col) == false: ret "empty" end
    ret sheet.get_string(row, col)
end

func main(): int throw:
    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()
    ret 0
end
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.

Types

Style

#
struct Style

The style of a cell.

NameTypeDescription
boldbool = falseBold.
italicbool = falseItalic.
underlinebool = falseUnderlined.
font_namestr = "Calibri"The font name.
font_sizeint = 11The font size.
font_colorstr = ""The text colour as hex, such as FF0000.
bg_colorstr = ""The background colour.
align_hint = 0The horizontal alignment.
align_vint = 0The vertical alignment.
num_formatstr = ""The number display format, such as 0.00.
borderbool = falseA thin border on all four sides.
wrapbool = falseLong text breaks onto more lines inside the cell, and \n starts a new line.
excel-Cell.salam
import excel

func main:
    println excel.ColumnLabel(0),
        excel.ColumnLabel(25),
        excel.ColumnLabel(26),
        excel.ColumnLabel(703)
    println excel.ColumnIndex("A"), excel.ColumnIndex("AA"), excel.CellRef(4, 2)
    mut row := 0
    mut col := 0
    println excel.ParseCellRef("C5", row, col), row, col, excel.ParseCellRef("5C", row, col)
    serial := excel.EpochToSerial(0)
    println serial, excel.SerialToEpoch(45371.0)
    text := excel.NewStringCell(0, 0, "some text")
    number := excel.NewNumberCell(0, 1, 3.5)
    flag := excel.NewBoolCell(0, 2, false)
    date := excel.NewDateCell(0, 3, 0)
    formula := excel.NewFormulaCell(0, 4, "A1*2", 7.0)
    println text.kind == excel.CellString,
        number.num,
        flag.flag,
        date.kind == excel.CellDate,
        formula.formula,
        formula.num
    println excel.CellEmpty, excel.CellNumber, excel.CellBool, excel.CellFormula
    mut styles := excel.NewStyleSheet()
    bold := excel.Style { bold = true, bg_color = "FFFF00", align_h = excel.AlignCenter }
    id := styles.GetOrAdd(bold)
    println id, styles.GetOrAdd(bold) == id, styles.count(), styles.Get(id).bold
    println bold.equals(styles.Get(id)), bold.font_name, bold.font_size
    println excel.AlignDefault,
        excel.AlignLeft,
        excel.AlignRight,
        excel.AlignTop,
        excel.AlignMiddle,
        excel.AlignBottom
    styles.Free()
end
Output
A Z AA AAB
0 26 C5
true 4 2 false
25569 1710892800
true 3.5 false true A1*2 7
0 2 3 5
1 true 2 true
true Calibri 11
0 1 3 1 2 3

Equals

#
func Equals(other: Style): bool

True when two styles are the same.

The example for this item is shown with the ones above: excel-Cell.salam

StyleSheet

#
struct StyleSheet

The table of unique styles.

NameTypeDescription
stylesVector<Style>The styles.

The example for this item is shown with the ones above: excel-Cell.salam

GetOrAdd

#
func GetOrAdd(s: Style): int

Returns the style index, adding it when it is new.

The example for this item is shown with the ones above: excel-Cell.salam

Get

#
func Get(id: int): Style

The style with the given index.

The example for this item is shown with the ones above: excel-Cell.salam

Count

#
func Count(): int

The number of styles.

The example for this item is shown with the ones above: excel-Cell.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: excel-Cell.salam

Workbook

#
struct Workbook

A workbook: several sheets, the style table and the file format.

NameTypeDescription
sheetsVector<Sheet>The sheets in order.
stylesStyleSheetThe styles shared by the cells.
active_sheetint = 0The index of the active sheet.
source_pathstr = ""The path of the file the workbook was read from.
formatint = 0The file format; one of the Format constants.
last_errorstr = ""The last error message.
excel-Workbook.salam
import excel

func main:
    mut book := excel.NewWorkbook()
    mut a := book.add_sheet("A")
    a.set_string(0, 0, "hello")
    a.set_number(0, 1, 2.5)
    mut b := book.add_sheet("B")
    b.set_int(0, 0, 42)
    println book.sheet_count(), book.sheet_names(), book.sheet_index("B"), book.sheet_at(0).name
    println book.rename_sheet(1, "second"), book.sheet("second").GetNumber(0, 0)
    println book.set_active(1), book.active().name, book.active_sheet
    println excel.WriteXLSX(book, "book.xlsx"),
        excel.WriteODS(book, "book.ods"),
        book.save("copy.xlsx"),
        excel.Save(book, "book.csv")
    println excel.DetectFormat("book.xlsx") == excel.FormatXLSX,
        excel.DetectFormat("book.ods") == excel.FormatODS,
        excel.DetectFormat("a.txt"),
        excel.FormatXLS,
        excel.FormatCSV,
        excel.FormatUnknown
    mut ok := false
    mut err := ""
    mut read := excel.Open("book.xlsx", ok, err)
    println ok,
        read.sheet_names(),
        read.sheet("A").get_string(0, 0),
        read.format == excel.FormatXLSX
    mut copy := excel.ReadXLSX("copy.xlsx", ok, err)
    mut ods := excel.ReadODS("book.ods", ok, err)
    println ok, ods.sheet("second").GetNumber(0, 0), copy.sheet_count()
    mut meta := excel.Inspect("book.xlsx", ok, err)
    println ok, meta.exists, meta.size > 0, meta.sheet_names, meta.sheet_rows, meta.sheet_cols
    meta.Free()
    mut csv := excel.ReadCSVWorkbook("book.csv", ok, err)
    println ok, csv.sheet_at(0).get_string(0, 0), excel.WriteCSVWorkbook(csv, "again.csv")
    _ := excel.Open("missing.xlsx", ok, err)
    println ok, err != ""
    _ := excel.ReadXLS("missing.xls", ok, err)
    println ok, excel.IsXLS(null, 0)
    println book.remove_sheet_named("A"),
        book.remove_sheet(5),
        book.remove_sheet(0),
        book.sheet_count()
    mut fresh := excel.New()
    println fresh.sheet_count()
    fresh.Free()
    read.Free()
    copy.Free()
    ods.Free()
    csv.Free()
    book.Free()
end
Output
2 ["A", "B"] 1 A
true 42
true second 1
true true true true
true true 0 2 4 0
true ["A", "second"] hello true
true 42 2
true true true ["A", "second"] [1, 1] [2, 1]
true 42 true
false true
false false
true false true 0
0

AddSheet

#
func AddSheet(name: str): Sheet*

Adds a new sheet under the given name and returns it.

The example for this item is shown with the ones above: excel-Workbook.salam

RemoveSheet

#
func RemoveSheet(idx: int): bool

Deletes sheet number idx; false when the index is wrong.

The example for this item is shown with the ones above: excel-Workbook.salam

RemoveSheetNamed

#
func RemoveSheetNamed(name: str): bool

Deletes the sheet by its name.

The example for this item is shown with the ones above: excel-Workbook.salam

RenameSheet

#
func RenameSheet(idx: int, new_name: str): bool

Renames the sheet.

The example for this item is shown with the ones above: excel-Workbook.salam

SheetIndex

#
func SheetIndex(name: str): int

The index of the sheet with this name; -1 when there is none.

The example for this item is shown with the ones above: excel-Workbook.salam

SheetCount

#
func SheetCount(): int

The number of sheets.

The example for this item is shown with the ones above: excel-Workbook.salam

SheetNames

#
func SheetNames(): Vector<str>

The sheet names in order.

The example for this item is shown with the ones above: excel-Workbook.salam

SheetAt

#
func SheetAt(idx: int): Sheet*

Sheet number idx.

The example for this item is shown with the ones above: excel-Workbook.salam

Sheet

#
func Sheet(name: str): Sheet*

The sheet with the given name.

The example for this item is shown with the ones above: excel-Workbook.salam

Active

#
func Active(): Sheet*

The active sheet.

The example for this item is shown with the ones above: excel-Workbook.salam

SetActive

#
func SetActive(idx: int): bool

Sets the active sheet.

The example for this item is shown with the ones above: excel-Workbook.salam

Save

#
func Save(path: str): bool

Saves the workbook; the format comes from the path extension.

The example for this item is shown with the ones above: excel-Workbook.salam

Free

#
func Free()

Frees the memory of the workbook.

The example for this item is shown with the ones above: excel-Workbook.salam

Cell

#
struct Cell

One cell.

NameTypeDescription
rowint = 0The row, from zero.
colint = 0The column, from zero.
kindint = 0The kind; one of the Cell constants.
textstr = ""The text of a string cell, or the error code.
numf64 = 0The number; for a date, the Excel serial number.
flagbool = falseThe boolean value.
formulastr = ""The formula text.
style_idint = -1The style index; -1 means the default.

The example for this item is shown with the ones above: excel-Cell.salam

CellPos

#
struct CellPos

The place of one cell.

NameTypeDescription
rowint = 0The row.
colint = 0The column.
excel-Sheet.salam
import excel

func main:
    mut sheet := excel.NewSheet("sales")
    sheet.set_string(0, 0, "item")
    sheet.set_string(0, 1, "count")
    sheet.set_cell(1, 0, "tea")
    sheet.set_int(1, 1, 12)
    sheet.set_cell(2, 0, "sugar")
    sheet.set_number(2, 1, 4.5)
    sheet.set_bool(3, 0, true)
    sheet.set_date(3, 1, 1710943509)
    sheet.set_formula(4, 1, "SUM(B2:B3)", 16.5)
    sheet.set_error(5, 0, "#DIV/0!")
    println sheet.name, sheet.row_count(), sheet.col_count()
    println sheet.get_string(1, 0),
        sheet.GetNumber(1, 1),
        sheet.GetNumber(2, 1),
        sheet.get_bool(3, 0),
        sheet.get_formula(4, 1)
    cell := sheet.get_cell(5, 0)
    println cell.kind == excel.CellError, cell.text, sheet.get_cell(3, 1).kind == excel.CellDate
    println sheet.has_cell(1, 1), sheet.has_cell(9, 9)
    sheet.clear_cell(5, 0)
    println sheet.has_cell(5, 0)
    mut row := Vector {} as Vector<str>
    row.Push("bread")
    row.Push("7")
    sheet.set_row(6, row)
    sheet.set_column(3, row)
    mut table := Vector {} as Vector<str>
    each value in ["a", "b", "c", "d"]:
        table.Push(value)
    end
    sheet.set_table(8, 0, table, 2)
    println sheet.get_row(6).Len(), sheet.get_column(3).Len(), sheet.get_all().Len()
    println sheet.get_string(9, 1)
    found := sheet.Find("bread")
    println found.Len(), found[0].row, found[0].col
    println sheet.filter_rows_equals(0, "tea")
    sheet.merge_cells(0, 0, 0, 1)
    mut hit := false
    range := sheet.merged_range(0, 1, hit)
    println sheet.is_merged(0, 1), hit, range.row1, range.col2, sheet.merges.Len()
    sheet.set_style(1, 1, 2)
    println sheet.get_cell(1, 1).style_id, sheet.max_row, sheet.max_col, sheet.cells.Size() > 0
    sheet.Free()
end
Output
sales 6 2
tea 12 4.5 true SUM(B2:B3)
true #DIV/0! true
true false
false
4 10 40
d
2 0 3
[1]
true true 0 1 1
2 9 3 true

MergeRange

#
struct MergeRange

A merged range.

NameTypeDescription
row1int = 0The starting row.
col1int = 0The starting column.
row2int = 0The ending row.
col2int = 0The ending column.

The example for this item is shown with the ones above: excel-Sheet.salam

Sheet

#
struct Sheet

One sheet: cells by row and column, from zero.

NameTypeDescription
namestr = ""The sheet name.
cellsHashMap<str, Cell>The cells by their reference.
max_rowint = -1The greatest filled row number; -1 for an empty sheet.
max_colint = -1The greatest filled column number.
mergesVector<MergeRange>The merged ranges.
rtlbool = falseShows the sheet right to left, as for Persian or Arabic data. It is written to xlsx files only.
freeze_rowsint = 0How many top rows stay in view while scrolling; set it with freeze. It is written to xlsx files only.
freeze_colsint = 0How many of the first columns stay in view while scrolling.
col_widthsVector<f64>The column widths in characters, by column number; 0 keeps the default width. They are written to xlsx files only.
auto_filterstr = ""The range that has filter buttons, such as A1:F20; empty for none. It is also read back from xlsx files.

The example for this item is shown with the ones above: excel-Sheet.salam

SetString

#
func SetString(row: int, col: int, value: str)

Makes the cell a string.

The example for this item is shown with the ones above: excel-Sheet.salam

SetCell

#
func SetCell(row: int, col: int, value: str)

The same as set_string; the value is stored as a string.

The example for this item is shown with the ones above: excel-Sheet.salam

SetNumber

#
func SetNumber(row: int, col: int, value: f64)

Makes the cell a float.

The example for this item is shown with the ones above: excel-Sheet.salam

SetInt

#
func SetInt(row: int, col: int, value: i64)

Makes the cell an integer.

The example for this item is shown with the ones above: excel-Sheet.salam

SetBool

#
func SetBool(row: int, col: int, value: bool)

Makes the cell a boolean.

The example for this item is shown with the ones above: excel-Sheet.salam

SetDate

#
func SetDate(row: int, col: int, epoch: i64)

Makes the cell a date; the instant in seconds since the Unix epoch.

The example for this item is shown with the ones above: excel-Sheet.salam

SetFormula

#
func SetFormula(row: int, col: int, formula: str, cached: f64)

Puts a formula and its last calculated result; Salam does not evaluate the formula.

The example for this item is shown with the ones above: excel-Sheet.salam

SetError

#
func SetError(row: int, col: int, code: str)

Makes the cell an error with the given code, such as #DIV/0!.

The example for this item is shown with the ones above: excel-Sheet.salam

SetStyle

#
func SetStyle(row: int, col: int, style_id: int)

Sets the style index of the cell.

The example for this item is shown with the ones above: excel-Sheet.salam

ClearCell

#
func ClearCell(row: int, col: int)

Empties the cell.

The example for this item is shown with the ones above: excel-Sheet.salam

HasCell

#
func HasCell(row: int, col: int): bool

True when the cell holds a value.

The example for this item is shown with the ones above: excel-Sheet.salam

GetCell

#
func GetCell(row: int, col: int): Cell

The cell itself; for an empty one, a cell of the empty kind.

The example for this item is shown with the ones above: excel-Sheet.salam

GetString

#
func GetString(row: int, col: int): str

The string value of the cell.

The example for this item is shown with the ones above: excel-Sheet.salam

GetNumber

#
func GetNumber(row: int, col: int): f64

The numeric value of the cell; zero for a string cell, even when its text is a number.

The example for this item is shown with the ones above: excel-Sheet.salam

GetBool

#
func GetBool(row: int, col: int): bool

The boolean value of the cell.

The example for this item is shown with the ones above: excel-Sheet.salam

GetFormula

#
func GetFormula(row: int, col: int): str

The formula text of the cell.

The example for this item is shown with the ones above: excel-Sheet.salam

RowCount

#
func RowCount(): int

The number of rows up to the last filled one.

The example for this item is shown with the ones above: excel-Sheet.salam

ColCount

#
func ColCount(): int

The number of columns up to the last filled one.

The example for this item is shown with the ones above: excel-Sheet.salam

SetRow

#
func SetRow(row: int, values: Vector<str>)

Fills a row from the left with the values.

The example for this item is shown with the ones above: excel-Sheet.salam

SetColumn

#
func SetColumn(col: int, values: Vector<str>)

Fills a column from the top.

The example for this item is shown with the ones above: excel-Sheet.salam

SetTable

#
func SetTable(start_row: int, start_col: int, flat: Vector<str>, num_cols: int)

Fills a table from a starting cell; the values one after another, num_cols of them per row.

The example for this item is shown with the ones above: excel-Sheet.salam

GetRow

#
func GetRow(row: int): Vector<Cell>

The filled cells of one row.

The example for this item is shown with the ones above: excel-Sheet.salam

GetColumn

#
func GetColumn(col: int): Vector<Cell>

The filled cells of one column.

The example for this item is shown with the ones above: excel-Sheet.salam

GetAll

#
func GetAll(): Vector<Cell>

Every filled cell.

The example for this item is shown with the ones above: excel-Sheet.salam

Find

#
func Find(value: str): Vector<CellPos>

The places of every cell whose text equals the value.

The example for this item is shown with the ones above: excel-Sheet.salam

FilterRowsEquals

#
func FilterRowsEquals(col: int, value: str): Vector<int>

The numbers of the rows whose given column equals the value.

The example for this item is shown with the ones above: excel-Sheet.salam

MergeCells

#
func MergeCells(row1: int, col1: int, row2: int, col2: int)

Merges a range of cells.

The example for this item is shown with the ones above: excel-Sheet.salam

IsMerged

#
func IsMerged(row: int, col: int): bool

True when the cell is part of a merged range.

The example for this item is shown with the ones above: excel-Sheet.salam

MergedRange

#
func MergedRange(row: int, col: int, found &: bool): MergeRange

The merged range the cell sits in.

The example for this item is shown with the ones above: excel-Sheet.salam

SetColumnWidth

#
func SetColumnWidth(col: int, width: f64)

Sets the width of a column in characters; 0 keeps the default.

excel-View.salam
import excel

func main:
    mut book := excel.NewWorkbook()
    mut sheet := book.add_sheet("prices")
    sheet.set_string(0, 0, "item")
    sheet.set_string(0, 1, "price")
    sheet.set_string(1, 0, "green tea, 500 g")
    sheet.set_number(1, 1, 4.5)
    sheet.set_string(2, 0, "sugar")
    sheet.set_number(2, 1, 1.25)
    sheet.rtl = true
    sheet.freeze(1, 1)
    sheet.set_auto_filter(0, 0, 2, 1)
    println sheet.rtl, sheet.freeze_rows, sheet.freeze_cols, sheet.auto_filter
    sheet.auto_fit()
    println sheet.col_widths
    sheet.set_column_width(3, 30.0)
    println sheet.col_widths.Len(), sheet.col_widths[2], sheet.col_widths[3]
    framed := excel.Style { border = true, wrap = true }
    id := book.styles.GetOrAdd(framed)
    sheet.set_style(0, 0, id)
    println excel.WriteXLSX(book, "prices.xlsx")
    mut ok := false
    mut err := ""
    mut read := excel.Open("prices.xlsx", ok, err)
    if ok:
        back := read.sheet("prices")
        println ok, back.auto_filter, read.styles.Get(back.get_cell(0, 0).style_id).wrap
    else:
        println ok, err
    end
    read.Free()
    book.Free()
end
Output
true 1 1 A1:B3
[21.2, 8]
4 0 30
true
true A1:B3 true

AutoFit

#
func AutoFit()

Sizes every column to its longest value, counted in characters, between 6 and 80; merged cells are skipped. Call it once the cells are filled.

The example for this item is shown with the ones above: excel-View.salam

Freeze

#
func Freeze(rows: int, cols: int)

Keeps the given number of top rows and first columns in view while scrolling; freeze(1, 0) pins a header row.

The example for this item is shown with the ones above: excel-View.salam

SetAutoFilter

#
func SetAutoFilter(row1: int, col1: int, row2: int, col2: int)

Puts filter buttons on the first row of a range, given by the row and column of its two corners.

The example for this item is shown with the ones above: excel-View.salam

Free

#
func Free()

Frees the memory of the sheet.

The example for this item is shown with the ones above: excel-Sheet.salam

FileMeta

#
struct FileMeta

The details of a spreadsheet file, without reading all of it.

NameTypeDescription
pathstr = ""The path.
formatint = 0The format.
existsbool = falseThe file is there.
sizei64 = 0The size in bytes.
sheet_namesVector<str>The sheet names.
sheet_rowsVector<int>The number of rows of each sheet.
sheet_colsVector<int>The number of columns of each sheet.

The example for this item is shown with the ones above: excel-Workbook.salam

Free

#
func Free()

Frees the memory.

The example for this item is shown with the ones above: excel-Workbook.salam

Constants and variables

Alignment

Align…#

The values of the style align_h (left, centre, right) and align_v (top, middle, bottom). Zero means the default.

NameValue
AlignDefault
0
AlignLeft
1
AlignCenter
2
AlignRight
3
AlignTop
1
AlignMiddle
2
AlignBottom
3

The example for this item is shown with the ones above: excel-Cell.salam

Cell kinds

Cell…#

The kind of each cell.

NameValue
CellEmpty
0
CellString
1
CellNumber
2
CellBool
3
CellDate
4
CellFormula
5
CellError
6

The example for this item is shown with the ones above: excel-Cell.salam

File formats

Format…#

The formats a workbook reads and writes.

NameValue
FormatUnknown
0
FormatXLSX
1
FormatXLS
2
FormatODS
3
FormatCSV
4

The example for this item is shown with the ones above: excel-Workbook.salam

Functions

NewStyleSheet

#
func NewStyleSheet(): StyleSheet

An empty style table.

The example for this item is shown with the ones above: excel-Cell.salam

IsXLS

#
func IsXLS(p: void*, n: int): bool

True when the bytes carry the xls file signature.

The example for this item is shown with the ones above: excel-Workbook.salam

ReadXLS

#
func ReadXLS(path: str, ok &: bool, err &: str): Workbook

Not supported yet: always sets ok false, with an err that suggests converting the file to xlsx or ods.

The example for this item is shown with the ones above: excel-Workbook.salam

NewWorkbook

#
func NewWorkbook(): Workbook

An empty workbook.

The example for this item is shown with the ones above: excel-Workbook.salam

ReadXLSX

#
func ReadXLSX(path: str, ok &: bool, err &: str): Workbook

Reads an xlsx file, Excel 2007 and later.

The example for this item is shown with the ones above: excel-Workbook.salam

ReadODS

#
func ReadODS(path: str, ok &: bool, err &: str): Workbook

Reads an ods file, from LibreOffice and OpenOffice.

The example for this item is shown with the ones above: excel-Workbook.salam

NewStringCell

#
func NewStringCell(row: int, col: int, value: str): Cell

A new string cell at the given row and column.

The example for this item is shown with the ones above: excel-Cell.salam

NewNumberCell

#
func NewNumberCell(row: int, col: int, value: f64): Cell

A new numeric cell at the given row and column.

The example for this item is shown with the ones above: excel-Cell.salam

NewBoolCell

#
func NewBoolCell(row: int, col: int, value: bool): Cell

A new boolean cell at the given row and column.

The example for this item is shown with the ones above: excel-Cell.salam

NewDateCell

#
func NewDateCell(row: int, col: int, epoch: i64): Cell

A new date cell from a Unix instant.

The example for this item is shown with the ones above: excel-Cell.salam

NewFormulaCell

#
func NewFormulaCell(row: int, col: int, formula: str, cached: f64): Cell

A formula cell with its calculated result.

The example for this item is shown with the ones above: excel-Cell.salam

ColumnLabel

#
func ColumnLabel(col: int): str

Turns a column number, from zero, into the Excel column letters: zero is A, 25 is Z, 26 is AA.

The example for this item is shown with the ones above: excel-Cell.salam

ColumnIndex

#
func ColumnIndex(label: str): int

Turns column letters into a column number.

The example for this item is shown with the ones above: excel-Cell.salam

CellRef

#
func CellRef(row: int, col: int): str

A cell reference, such as C5, from a zero based row and column.

The example for this item is shown with the ones above: excel-Cell.salam

ParseCellRef

#
func ParseCellRef(ref: str, row_out &: int, col_out &: int): bool

Turns a reference such as C5 into a zero based row and column.

The example for this item is shown with the ones above: excel-Cell.salam

EpochToSerial

#
func EpochToSerial(epoch: i64): f64

Turns a Unix instant into an Excel date serial number, days since 1899-12-30.

The example for this item is shown with the ones above: excel-Cell.salam

SerialToEpoch

#
func SerialToEpoch(serial: f64): i64

Turns an Excel serial number into a Unix instant.

The example for this item is shown with the ones above: excel-Cell.salam

NewSheet

#
func NewSheet(name: str): Sheet

An empty sheet on its own, outside a workbook; for conversions.

The example for this item is shown with the ones above: excel-Sheet.salam

SheetToJSON

#
func SheetToJSON(sheet: Sheet): str

Turns a sheet into an array of rows, each row an array of strings.

excel-Convert.salam
import excel

func main throw:
    mut sheet := try excel.CSVToSheet("name,score\nAli,17\n\"Sara, A\",19.5\n", "scores")
    println sheet.name, sheet.row_count(), sheet.get_string(2, 0), sheet.GetNumber(2, 1)
    println excel.SheetToCSV(sheet)
    println excel.SheetToJSON(sheet)
    mut from_json := excel.JSONToSheet(`[["a", "b"], ["1", "x"], ["2", "y"]]`, "data")
    println from_json.row_count(),
        from_json.col_count(),
        from_json.get_string(0, 1),
        from_json.get_string(2, 0)
    xml := "<row r=\"2\"><c r=\"A2\" t=\"s\"><v>0</v></c><br/></row>"
    start := excel.XmlFind(xml, "c", 0)
    println start, excel.XmlAttr(xml, start, "r"), excel.XmlTagEnd(xml, start)
    println excel.XmlInner(xml, "v", 0), excel.XmlSelfClosing(xml, excel.XmlFind(xml, "br", 0))
    println excel.XmlFindClose(xml, "row", 10)
    println excel.XmlEscape("a<b&c"), excel.XmlUnescape("a&lt;b&amp;c")
    sheet.Free()
    from_json.Free()
end
Output
scores 3 Sara, A 0
name,score
Ali,17
"Sara, A",19.5
[["name", "score"], ["Ali", "17"], ["Sara, A", "19.5"]]
3 2 b 2
11 A2 27
0 true
44
a&lt;b&amp;c a<b&c

JSONToSheet

#
func JSONToSheet(text: str, sheet_name: str): Sheet

Turns an array of string arrays into a sheet.

The example for this item is shown with the ones above: excel-Convert.salam

XmlEscape

#
func XmlEscape(s: str): str

Escapes the special XML characters.

The example for this item is shown with the ones above: excel-Convert.salam

XmlUnescape

#
func XmlUnescape(s: str): str

Undoes XML escaping.

The example for this item is shown with the ones above: excel-Convert.salam

XmlFind

#
func XmlFind(xml: str, tag: str, from: int): int

The place of the opening tag with the given name, from from onwards.

The example for this item is shown with the ones above: excel-Convert.salam

XmlTagEnd

#
func XmlTagEnd(xml: str, start: int): int

The place of the closing > of the tag that starts at start.

The example for this item is shown with the ones above: excel-Convert.salam

XmlSelfClosing

#
func XmlSelfClosing(xml: str, start: int): bool

True when the tag is self closing.

The example for this item is shown with the ones above: excel-Convert.salam

XmlAttr

#
func XmlAttr(xml: str, start: int, attr: str): str

The value of one tag attribute.

The example for this item is shown with the ones above: excel-Convert.salam

XmlFindClose

#
func XmlFindClose(xml: str, tag: str, content_start: int): int

The place of the matching closing tag.

The example for this item is shown with the ones above: excel-Convert.salam

XmlInner

#
func XmlInner(xml: str, tag: str, from: int): str

The text inside the first element with the given name.

The example for this item is shown with the ones above: excel-Convert.salam

WriteXLSX

#
func WriteXLSX(book &: Workbook, path: str): bool

Writes the workbook as xlsx.

The example for this item is shown with the ones above: excel-Workbook.salam

DetectFormat

#
func DetectFormat(path: str): int

Works out the file format from the extension alone, ignoring case; the contents are not read.

The example for this item is shown with the ones above: excel-Workbook.salam

New

#
func New(): Workbook

An empty workbook; the same as NewWorkbook.

The example for this item is shown with the ones above: excel-Workbook.salam

Open

#
func Open(path: str, ok &: bool, err &: str): Workbook

Opens an xlsx, ods, xls or csv file, chosen by the extension. When it fails, ok is false and err holds the message.

The example for this item is shown with the ones above: excel-Workbook.salam

Save

#
func Save(book &: Workbook, path: str): bool

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.

The example for this item is shown with the ones above: excel-Workbook.salam

WriteODS

#
func WriteODS(book &: Workbook, path: str): bool

Writes the workbook as ods.

The example for this item is shown with the ones above: excel-Workbook.salam

SheetToCSV

#
func SheetToCSV(sheet: Sheet): str

Turns a sheet into CSV text.

The example for this item is shown with the ones above: excel-Convert.salam

CSVToSheet

#
func CSVToSheet(text: str, sheet_name: str): Throws<Sheet>

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.

The example for this item is shown with the ones above: excel-Convert.salam

ReadCSVWorkbook

#
func ReadCSVWorkbook(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.

The example for this item is shown with the ones above: excel-Workbook.salam

WriteCSVWorkbook

#
func WriteCSVWorkbook(book &: Workbook, path: str): bool

Writes the active sheet as CSV.

The example for this item is shown with the ones above: excel-Workbook.salam

Inspect

#
func Inspect(path: str, ok &: bool, err &: str): FileMeta

Tells you the format, the sheets and the size of each sheet of a file. It opens the whole workbook to do so.

The example for this item is shown with the ones above: excel-Workbook.salam