59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
from openpyxl import load_workbook, Workbook
|
|
from typing import List
|
|
from pydantic import BaseModel
|
|
|
|
class CellData(BaseModel):
|
|
value: str
|
|
font: dict
|
|
fill: dict
|
|
border: dict
|
|
alignment: dict
|
|
|
|
class SheetData(BaseModel):
|
|
name: str
|
|
cells: List[List[CellData]]
|
|
|
|
def read_excel(file_path: str) -> List[SheetData]:
|
|
workbook = load_workbook(file_path)
|
|
sheets_data = []
|
|
|
|
for sheet in workbook.sheetnames:
|
|
ws = workbook[sheet]
|
|
cells_data = []
|
|
|
|
for row in ws.iter_rows():
|
|
row_data = []
|
|
for cell in row:
|
|
cell_data = CellData(
|
|
value=cell.value,
|
|
font=cell.font.__dict__,
|
|
fill=cell.fill.__dict__,
|
|
border=cell.border.__dict__,
|
|
alignment=cell.alignment.__dict__
|
|
)
|
|
row_data.append(cell_data)
|
|
cells_data.append(row_data)
|
|
|
|
sheets_data.append(SheetData(name=sheet, cells=cells_data))
|
|
|
|
return sheets_data
|
|
|
|
def write_excel(file_path: str, sheets_data: List[SheetData]):
|
|
workbook = Workbook()
|
|
|
|
for sheet_data in sheets_data:
|
|
ws = workbook.create_sheet(title=sheet_data.name)
|
|
|
|
for row_index, row in enumerate(sheet_data.cells):
|
|
for col_index, cell_data in enumerate(row):
|
|
cell = ws.cell(row=row_index + 1, column=col_index + 1, value=cell_data.value)
|
|
cell.font = cell_data.font
|
|
cell.fill = cell_data.fill
|
|
cell.border = cell_data.border
|
|
cell.alignment = cell_data.alignment
|
|
|
|
# Remove the default sheet created by Workbook
|
|
if "Sheet" in workbook.sheetnames:
|
|
del workbook["Sheet"]
|
|
|
|
workbook.save(file_path) |