Index CSV and XLSX Documents
Upload a spreadsheet, retrieve its cells as JSON, and write selected rows to a typed Antfly table
Store each file as a source document. The document extraction artifact publishes one child unit per CSV file or XLSX worksheet, in workbook order. Each unit has searchable text and a positional JSON grid. When you know the columns you need, you can project rows into a second Antfly table with its own JSON Schema.
Upload a workbook and a CSV
Start a local Antfly server on port 8080. Run the Python blocks in order in one
session using the Python SDK from this checkout and openpyxl to create the
example workbook. From the repository root, install them with
python -m pip install ./py/packages/sdk openpyxl.
import base64
import json
from io import BytesIO
from antfly import AntflyClient, TableColumn, project_table_rows
from openpyxl import Workbook
client = AntflyClient("http://localhost:8080")
files = "inventory_files"
artifact = "units"
client.create_table(files, num_shards=1)
client.put_artifact_enrichment(files, artifact, {
"kind": "asset",
"field": "url",
"content_type": "application/json",
"producer_json": json.dumps({
"type": "document_extraction",
"config": {"source": {
"filename_field": "filename",
"content_type_field": "mime_type",
}},
}),
})
def source(filename, mime, data):
encoded = base64.b64encode(data).decode("ascii")
return {"filename": filename, "mime_type": mime,
"url": f"data:{mime.split(';')[0]};base64,{encoded}"}
book = Workbook()
sheet = book.active
sheet.title = "Items"
book.create_sheet("Notes", 0).append(["Inventory count"])
sheet.append(["SKU", "Qty", "Active"])
sheet.append([12, 4, False])
sheet.append(["0024", 7, True])
sheet["A2"].number_format = "0000"
buffer = BytesIO()
book.save(buffer)
xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
client.batch(files, inserts={
"stock-xlsx": source("stock.xlsx", xlsx, buffer.getvalue()),
"stock-csv": source("stock.csv", "text/csv; header=present",
b"SKU,Qty,Active\r\n0012,4,false\r\n"),
}, sync_level="write")
Retrieve the grid
Extraction runs asynchronously. The SDK can wait for the named artifact to
finish and page through its units in workbook order. Use the worksheet name in
source_path to select a sheet.
def items_sheet(**options):
units = client.document_units(files, "stock-xlsx", artifact=artifact,
wait_timeout=60, page_size=1, **options)
return next(unit for unit in units if unit["source_path"] == "Items")
unit = items_sheet()
grid = unit["tables"][0]
sku = next(c for c in grid["cells"] if (c["row"], c["column"]) == (1, 0))
print(unit["source_path"], sku["text"], sku["value"]) # Items 0012 12
csv_unit, = client.document_units(files, "stock-csv", artifact=artifact, wait_timeout=60)
csv_grid = csv_unit["tables"][0]
assert csv_grid["cells"][0]["header"]
A table has a unit-local id, rows, columns, and a sparse cells array.
Coordinates start at zero. An omitted row or column span defaults to one.
Repeated or blank column labels retain their positions. CSV fields preserve
empty strings, embedded newlines, and leading zeros. Setting
text/csv; header=present marks the first record as headers. A CSV over the
one-million-cell limit still publishes its text with an empty tables array
and a csv_cell_limit_exceeded finding. If an encoded grid exceeds the byte
budget left after the unit text, the unit reports csv_grid_byte_limit_exceeded
or xlsx_grid_byte_limit_exceeded and publishes an empty grid array.
Write typed inventory rows
Use the displayed SKU to keep its leading zeros. Select the workbook's native values for quantity and active status to preserve their JSON types.
lines = "inventory_lines"
client.create_table(lines, num_shards=1, schema={
"default_type": "line",
"document_schemas": {"line": {"schema": {
"type": "object",
"properties": {
"sku": {"type": "string"},
"quantity": {"type": "integer"},
"active": {"type": "boolean"},
"source": {"type": "object"},
},
}}},
})
published_keys = {}
scope = (files, "stock-xlsx", artifact, "Items", lines)
def replace_items(unit):
rows = dict(project_table_rows(
unit, source_table=files, document="stock-xlsx", artifact=artifact, header_row=0,
unit_key=unit["source_path"],
columns={"sku": TableColumn("SKU"), "quantity": TableColumn("Qty", source="value"),
"active": TableColumn("Active", source="value")},
))
old_keys = published_keys.get(scope, set())
removed = old_keys - rows.keys()
outcome = client.batch(lines, inserts=rows, deletes=sorted(removed), sync_level="write")
if outcome.status != "committed":
raise RuntimeError(f"Check batch outcome before advancing the import: {outcome.status}")
published_keys[scope] = set(rows)
return rows, removed
rows, _ = replace_items(unit)
row = next(iter(rows.values()))
assert (row["sku"], row["quantity"], row["active"]) == ("0012", 4, False)
The key includes the source table, document key, artifact, worksheet name,
table ID, and row position. Using the worksheet name as unit_key keeps
independent imports stable when worksheets move. The source object records
the current worksheet ordinal and name. Choose a column by zero-based index
when labels repeat. CSV and OCR supply displayed text. For a CSV integer, use TableColumn("Qty", convert=int).
A sparse coordinate omits the mapped field. An explicit cell without the
requested native value raises a conversion error with its coordinates. XLSX
formula cells expose the expression and the cached result when present. For
shared formulas, match shared_formula_id within the sheet to the cell that
holds the anchor expression. Followers retain their own cached values when
available. The shared_formula_reference finding signals that followers refer
to the anchor. A missing group ID or anchor produces an
unresolved_shared_formula finding. Formula evaluation stays with the workbook
application.
Replace rows after a workbook edit
The workbook's data URL identifies the exact bytes being imported. Waiting for that URL accepts a completed identical upload and waits for changed content. For remote files use an immutable, version-specific URL. Serialize source writes and imports when multiple workers can replace the same workbook.
from antfly.exceptions import AntflyNotFoundError
def upload_and_import(data):
upload = source("stock.xlsx", xlsx, data)
client.batch(files, inserts={"stock-xlsx": upload}, sync_level="write")
return replace_items(items_sheet(expected_source_url=upload["url"]))
sheet.delete_rows(3)
book.move_sheet(sheet, offset=-1)
updated = BytesIO()
book.save(updated)
rows, removed = upload_and_import(updated.getvalue())
removed_key, = removed
try:
client.get(lines, removed_key)
except AntflyNotFoundError:
pass
else:
raise AssertionError("Removed inventory row still exists")
assert len(rows) == 1
repeated, removed_again = upload_and_import(updated.getvalue())
assert repeated == rows and not removed_again
For recurring imports, persist the last successful key set per source, worksheet, and destination, and serialize imports for that scope. Build the complete replacement before writing. A missing worksheet, missing grid, or conversion error then leaves the previous rows available for inspection.