Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions app/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import time
import warnings
import zipfile
from contextlib import closing
from datetime import date, datetime
from pathlib import Path
from xml.sax.saxutils import escape
Expand Down Expand Up @@ -279,23 +280,25 @@ def spreadsheet_pdf(job):
with zipfile.ZipFile(source) as archive:
if sum(entry.file_size for entry in archive.infolist()) > 200_000_000:
raise ConversionError("This workbook is too large when expanded.")
workbook = load_workbook(source, read_only=True, data_only=False, keep_links=False)
cached = load_workbook(source, read_only=True, data_only=True, keep_links=False)
try:
with (
closing(load_workbook(source, read_only=True, data_only=False, keep_links=False)) as workbook,
closing(load_workbook(source, read_only=True, data_only=True, keep_links=False)) as cached,
):
for sheet in workbook:
checkpoint(job)
if sheet.sheet_state != "visible":
continue
if sheet.max_row > 10000 or sheet.max_column > 80:
raise ConversionError("Table export supports up to 10,000 rows and 80 columns per sheet. Remove unused formatted rows if needed.")
values_sheet = cached[sheet.title]
# Read-only worksheets use the recorded range, which can omit actual cells.
sheet.reset_dimensions()
values_sheet.reset_dimensions()
rows = []
for cells, values in zip(sheet.iter_rows(), cached[sheet.title].iter_rows()):
for cells, values in zip(sheet.iter_rows(), values_sheet.iter_rows()):
checkpoint(job)
if len(rows) >= 10000 or len(cells) > 80:
raise ConversionError("Table export supports up to 10,000 rows and 80 columns per sheet. Remove unused formatted rows if needed.")
rows.append([cell_text(cell, value, job) for cell, value in zip(cells, values)])
sheets.append((sheet.title, rows))
finally:
workbook.close()
cached.close()
checkpoint(job)
page_size = landscape(A4) if job.options["orientation"] == "landscape" else A4
doc = SimpleDocTemplate(str(job.directory / f"{Path(job.filenames[0]).stem}.pdf"), pagesize=page_size,
Expand Down
27 changes: 23 additions & 4 deletions tests/test_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import pytest
from fastapi.testclient import TestClient
from openpyxl import Workbook
from PIL import Image
from pypdf import PdfReader, PdfWriter

Expand Down Expand Up @@ -60,15 +61,17 @@ def pdf_bytes(width):
return result.getvalue()


def workbook_bytes():
def workbook_bytes(dimension):
# Minimal OOXML fixture with cached and uncached formulas plus a hidden sheet.
result = io.BytesIO()
with zipfile.ZipFile(result, "w") as archive:
archive.writestr("[Content_Types].xml", '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/worksheets/sheet2.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>')
archive.writestr("_rels/.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>')
archive.writestr("xl/workbook.xml", '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sales" sheetId="1" r:id="rId1"/><sheet name="Hidden" sheetId="2" state="hidden" r:id="rId2"/></sheets></workbook>')
archive.writestr("xl/_rels/workbook.xml.rels", '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet2.xml"/></Relationships>')
archive.writestr("xl/worksheets/sheet1.xml", '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dimension ref="A1:C3"/><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>City</t></is></c><c r="B1" t="inlineStr"><is><t>Total</t></is></c><c r="C1" t="inlineStr"><is><t>Formula</t></is></c></row><row r="2"><c r="A2" t="inlineStr"><is><t>München</t></is></c><c r="B2"><f>SUM(20,22)</f><v>42</v></c><c r="C2"><f>SUM(B2,8)</f><v/></c></row><row r="3"><c r="A3" t="inlineStr"><is><t>Berlin</t></is></c><c r="B3"><v>31</v></c></row></sheetData></worksheet>')
dimensions = f'<dimension ref="{dimension}"/>' if dimension else ""
archive.writestr("xl/worksheets/sheet1.xml", '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
+ dimensions + '<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>City</t></is></c><c r="B1" t="inlineStr"><is><t>Total</t></is></c><c r="C1" t="inlineStr"><is><t>Formula</t></is></c></row><row r="2"><c r="A2" t="inlineStr"><is><t>München</t></is></c><c r="B2"><f>SUM(20,22)</f><v>42</v></c><c r="C2"><f>SUM(B2,8)</f><v/></c></row><row r="3"><c r="A3" t="inlineStr"><is><t>Berlin</t></is></c><c r="B3"><v>31</v></c></row></sheetData></worksheet>')
archive.writestr("xl/worksheets/sheet2.xml", '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dimension ref="A1"/><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Private hidden data</t></is></c></row></sheetData></worksheet>')
return result.getvalue()

Expand All @@ -90,16 +93,32 @@ def test_image_pdf_is_readable(client):
assert len(PdfReader(io.BytesIO(download(client, job))).pages) == 1


def test_xlsx_cached_formula_unicode_and_hidden_sheet(client):
job = wait(client, submit(client, "spreadsheet", [("sales.xlsx", workbook_bytes())])["id"])
@pytest.mark.parametrize("dimension", ["A1:C3", "A1", None])
def test_xlsx_cached_formula_unicode_and_hidden_sheet(client, dimension):
job = wait(client, submit(client, "spreadsheet", [("sales.xlsx", workbook_bytes(dimension))])["id"])
content = "\n".join(page.extract_text() for page in PdfReader(io.BytesIO(download(client, job))).pages)
assert "München" in content
assert "Berlin" in content
assert "42" in content
assert "=SUM(B2,8)" in content
assert "Private hidden data" not in content
assert any("no saved result" in warning for warning in job["warnings"])


@pytest.mark.parametrize("rows, columns", [(10001, 1), (1, 81)])
def test_xlsx_without_dimensions_enforces_export_limits(client, rows, columns):
workbook = Workbook(write_only=True)
sheet = workbook.create_sheet()
for _ in range(rows):
sheet.append(["data"] * columns)
result = io.BytesIO()
workbook.save(result)

job = wait(client, submit(client, "spreadsheet", [("wide.xlsx", result.getvalue())])["id"])
assert job["status"] == "failed"
assert "10,000 rows and 80 columns" in job["error"]


def test_wide_csv_pagination_does_not_drop_rows_or_columns(client):
rows = [",".join(f"Column{i}" for i in range(12))]
rows += [",".join(f"R{row}C{col}" for col in range(12)) for row in range(130)]
Expand Down
Loading