Adicionar app/services/io_excel.py
This commit is contained in:
@@ -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")
|
||||||
Reference in New Issue
Block a user