Spaces:
Sleeping
Sleeping
| import os | |
| from openpyxl import load_workbook | |
| import xlwt | |
| import gradio as gr | |
| import zipfile | |
| import tempfile | |
| import shutil | |
| def convert_xlsx_to_xls(xlsx_path, xls_path): | |
| try: | |
| wb_xlsx = load_workbook(xlsx_path, data_only=True) | |
| wb_xls = xlwt.Workbook() | |
| for sheet_name in wb_xlsx.sheetnames: | |
| ws_xlsx = wb_xlsx[sheet_name] | |
| ws_xls = wb_xls.add_sheet(sheet_name[:31]) # .xls sheet name limit is 31 | |
| for r_idx, row in enumerate(ws_xlsx.iter_rows(values_only=True)): | |
| for c_idx, value in enumerate(row): | |
| if value is not None: | |
| # Handle wide variety of types safely | |
| try: | |
| ws_xls.write(r_idx, c_idx, str(value) if isinstance(value, (dict, list, tuple)) else value) | |
| except Exception as e: | |
| ws_xls.write(r_idx, c_idx, str(value)) | |
| os.makedirs(os.path.dirname(xls_path), exist_ok=True) | |
| wb_xls.save(xls_path) | |
| except Exception as e: | |
| print(f"Error converting {xlsx_path} → {xls_path}: {e}") | |
| def process_zip(zip_file): | |
| temp_dir = tempfile.mkdtemp() | |
| output_dir = tempfile.mkdtemp() | |
| try: | |
| # Extract zip | |
| with zipfile.ZipFile(zip_file.name, 'r') as zip_ref: | |
| zip_ref.extractall(temp_dir) | |
| # Walk through and convert | |
| for root, _, files in os.walk(temp_dir): | |
| for file in files: | |
| if file.endswith(".xlsx"): | |
| xlsx_file = os.path.join(root, file) | |
| rel_path = os.path.relpath(xlsx_file, temp_dir) | |
| xls_path = os.path.join(output_dir, os.path.splitext(rel_path)[0] + ".xls") | |
| try: | |
| convert_xlsx_to_xls(xlsx_file, xls_path) | |
| except Exception as e: | |
| print(f"Failed to convert {xlsx_file}: {e}") | |
| # Repack output | |
| output_zip = os.path.join(tempfile.gettempdir(), "converted_xls.zip") | |
| with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as zipf: | |
| for root, _, files in os.walk(output_dir): | |
| for file in files: | |
| abs_file = os.path.join(root, file) | |
| rel_path = os.path.relpath(abs_file, output_dir) | |
| zipf.write(abs_file, rel_path) | |
| finally: | |
| shutil.rmtree(temp_dir, ignore_errors=True) | |
| shutil.rmtree(output_dir, ignore_errors=True) | |
| return output_zip | |
| demo = gr.Interface( | |
| fn=process_zip, | |
| inputs=gr.File(file_types=[".zip"], label="Upload ZIP with .xlsx files"), | |
| outputs=gr.File(label="Download Converted .xls ZIP"), | |
| title="XLSX to XLS Converter", | |
| description="Upload a ZIP of Excel .xlsx files. Get back a ZIP with .xls versions." | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |