Skip to content

Commit

Permalink
Set the sheet name when generating xlsx files
Browse files Browse the repository at this point in the history
  • Loading branch information
calpaterson committed Aug 8, 2024
1 parent 3146534 commit 239b442
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
8 changes: 7 additions & 1 deletion csvbase/svc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1002,7 +1002,13 @@ def populate_repcache(
elif content_type is ContentType.JSON_LINES:
table_io.rows_to_jsonlines(columns, rows, rep_file)
elif content_type is ContentType.XLSX:
table_io.rows_to_xlsx(columns, rows, excel_table=False, buf=rep_file)
table_io.rows_to_xlsx(
columns,
rows,
excel_table=False,
buf=rep_file,
sheet_name=table_io.make_xlsx_sheet_name(table),
)
else:
table_io.rows_to_csv(columns, rows, buf=rep_file)
logger.info("populated repcache for %s@%s", table.ref(), table.last_changed)
20 changes: 18 additions & 2 deletions csvbase/table_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from . import conv, exc
from .streams import UserSubmittedCSVData, rewind
from .value_objs import ColumnType, PythonType, Column
from .value_objs import ColumnType, PythonType, Column, Table
from .json import value_to_json

logger = getLogger(__name__)
Expand Down Expand Up @@ -184,9 +184,25 @@ def rows_to_csv(
return buf


def make_xlsx_sheet_name(table: Table) -> str:
"""Turn a table name into an excel sheet name, obeying the various
restrictions excel imposes on sheet names."""
max_length = 31

# slashes are not allowed, use semi-colon
sheet_name = ";".join([table.username, table.table_name])

# make it clear it's been abbreviated
if len(sheet_name) > max_length:
sheet_name = sheet_name[: max_length - 3] + "..."

return sheet_name


def rows_to_xlsx(
columns: Sequence[Column],
rows: Iterable[UnmappedRow],
sheet_name=None,
excel_table: bool = False,
buf: Optional[IO[bytes]] = None,
) -> IO[bytes]:
Expand All @@ -200,7 +216,7 @@ def rows_to_xlsx(
buf = buf or io.BytesIO()
with rewind(buf):
with xlsxwriter.Workbook(buf, workbook_args) as workbook:
worksheet = workbook.add_worksheet()
worksheet = workbook.add_worksheet(name=sheet_name)

if excel_table:
rows = list(rows)
Expand Down

0 comments on commit 239b442

Please sign in to comment.