# 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") def convert_xlsx_all_sheets(path): wb = openpyxl.load_workbook(path, data_only=True) results = {} for sheet_name in wb.sheetnames: ws = wb[sheet_name] rows = [] for row in ws.iter_rows(values_only=True): cleaned = [normalize_newlines(cell) for cell in row] rows.append("\x09".join(cleaned)) results[sheet_name] = "\n".join(rows) return results def convert_xls_all_sheets(path): wb = xlrd.open_workbook(path) results = {} for sheet in wb.sheets(): 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)) results[sheet.name] = "\n".join(rows) return results def convert_ods_all_sheets(path): doc = load(path) results = {} for table in doc.getElementsByType(Table): sheet_name = table.getAttribute("name") or "Sheet" rows = [] 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)) results[sheet_name] = "\n".join(rows) return results def convert_excel_all_sheets(path): if path.endswith(".xlsx"): return convert_xlsx_all_sheets(path) if path.endswith(".xls"): return convert_xls_all_sheets(path) if path.endswith(".ods"): return convert_ods_all_sheets(path) raise ValueError("Unsupported Excel format")