Spaces:
Running
Running
import pandas as pd | |
import os | |
import xlrd # Reads old .xls files | |
from openpyxl import Workbook | |
from openpyxl import load_workbook | |
from reportlab.pdfgen import canvas | |
from reportlab.lib.pagesizes import landscape, portrait, A0, A1, A2, A3, A4 | |
from reportlab.lib.colors import Color, black | |
def convert_xls_to_xlsx(xls_path): | |
"""Convert .xls to .xlsx while keeping all sheets and data intact.""" | |
if not xls_path.endswith(".xls"): | |
return xls_path | |
xlsx_path = xls_path.replace(".xls", ".xlsx") | |
# Open .xls file using xlrd | |
book = xlrd.open_workbook(xls_path) | |
new_book = Workbook() | |
new_book.remove(new_book.active) | |
for sheet_index in range(book.nsheets): | |
sheet = book.sheet_by_index(sheet_index) | |
new_sheet = new_book.create_sheet(title=sheet.name) | |
for row_idx in range(sheet.nrows): | |
for col_idx in range(sheet.ncols): | |
cell_value = sheet.cell(row_idx, col_idx).value | |
new_sheet.cell(row=row_idx + 1, column=col_idx + 1, value=cell_value) | |
new_book.save(xlsx_path) | |
print(f"Converted {xls_path} to {xlsx_path}") | |
return xlsx_path | |
def excel_to_pdf(excel_file, pdf_file = "output.pdf"): | |
excel_file = convert_xls_to_xlsx(excel_file) # Convert if .xls | |
workbook = load_workbook(excel_file, data_only=True) | |
c = canvas.Canvas(pdf_file) | |
for sheet_index, sheet in enumerate(workbook.worksheets): | |
print("hello") | |
num_columns = sheet.max_column | |
num_rows = sheet.max_row | |
page_size = A2 # page size, customize as needed | |
c.setPageSize(page_size) | |
if sheet_index > 0: | |
c.showPage() | |
page_width, page_height = page_size | |
y = page_height - 20 # Start from top | |
for row in sheet.iter_rows(): | |
x = 10 # Start from left | |
for cell in row: | |
c.drawString(x, y, str(cell.value or "")) | |
x += 150 # Adjust column width | |
y -= 20 # Adjust row height | |
c.save() | |