From 8a973ee7a7d3b7aea0dc9d743f660e1aa5bd10c4 Mon Sep 17 00:00:00 2001 From: Renato Rosa Date: Wed, 19 Aug 2026 21:44:38 -0300 Subject: [PATCH] Adicionar app/services/io_excel.py --- app/services/io_excel.py | 57 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 app/services/io_excel.py diff --git a/app/services/io_excel.py b/app/services/io_excel.py new file mode 100644 index 0000000..9354a32 --- /dev/null +++ b/app/services/io_excel.py @@ -0,0 +1,57 @@ +# All comments are in English. + +import openpyxl +import xlrd +from odf.opendocument import load +from odf.table import Table, TableRow, TableCell +from odf.text import P + +def normalize_newlines(value): + if value is None: + return "" + return ( + str(value) + .replace("\r\n", "\\n") + .replace("\n\r", "\\n") + .replace("\r", "\\n") + .replace("\n", "\\n") + ) + +def convert_xlsx(path): + wb = openpyxl.load_workbook(path, data_only=True) + ws = wb.active + rows = [] + for row in ws.iter_rows(values_only=True): + cleaned = [normalize_newlines(cell) for cell in row] + rows.append("\x09".join(cleaned)) + return "\n".join(rows) + +def convert_xls(path): + wb = xlrd.open_workbook(path) + sheet = wb.sheet_by_index(0) + rows = [] + for r in range(sheet.nrows): + cleaned = [normalize_newlines(sheet.cell_value(r, c)) for c in range(sheet.ncols)] + rows.append("\x09".join(cleaned)) + return "\n".join(rows) + +def convert_ods(path): + doc = load(path) + rows = [] + for table in doc.getElementsByType(Table): + for row in table.getElementsByType(TableRow): + cells = [] + for cell in row.getElementsByType(TableCell): + text = "".join(t.data for t in cell.getElementsByType(P)) + cells.append(normalize_newlines(text)) + rows.append("\x09".join(cells)) + return "\n".join(rows) + +def convert_excel(path): + if path.endswith(".xlsx"): + return convert_xlsx(path) + if path.endswith(".xls"): + return convert_xls(path) + if path.endswith(".ods"): + return convert_ods(path) + raise ValueError("Unsupported Excel format")