To achieve this, you can extend the openpyxl library by creating new classes that inherit from the base classes and add the functionality you need. Here's a basic implementation to get you started:
First, install the openpyxl library if you haven't already:
pip install openpyxl
Next, create a new Python script and import the required libraries:
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font
Now, create a new class that inherits from the openpyxl Cell class and adds the functionality you need:
class CustomCell(openpyxl.cell.Cell):
@property
def cell_parts(self):
cell_parts = {
"display_value": self.value,
"text_color": self.font.color,
"format": self.number_format,
"indentation": self.alignment.indent,
"highlighting": self.fill,
"sub_part": [],
}
# Add logic to split superscript, subscript or other characters into separate objects
# and append them to the 'sub_part' list.
return cell_parts
Then, create a new class that inherits from the openpyxl Worksheet class and replaces the Cell class with the CustomCell class:
class CustomWorksheet(openpyxl.worksheet.Worksheet):
def cell(self, row, column, value=None):
if not value:
value = CustomCell(self, row=row, column=column)
else:
value = CustomCell(self, row=row, column=column, value=value)
return value
Finally, create a new class that inherits from the openpyxl Workbook class and replaces the Worksheet class with the CustomWorksheet class:
class CustomWorkbook(openpyxl.Workbook):
def create_sheet(self, title=None, index=None):
if title is None:
title = self.sheetnames[0]
if index is None:
index = len(self._sheets)
new_sheet = CustomWorksheet(parent=self, title=title)
self._add_sheet(sheet=new_sheet, index=index)
return new_sheet
Now you can use the CustomWorkbook class to read an Excel document and access the additional properties:
def read_excel(file_path):
wb = CustomWorkbook()
wb = openpyxl.load_workbook(file_path)
result = {}
for sheet_name in wb.sheetnames:
ws = wb[sheet_name]
sheet_data = []
for row in ws.iter_rows():
row_data = []
for cell in row:
cell_parts = cell.cell_parts
row_data.append(cell_parts)
sheet_data.append(row_data)
result[sheet_name] = sheet_data
return result
Keep in mind that this is just a basic implementation, and you'll need to add the necessary logic to split superscript, subscript, or other characters into separate objects in the 'sub_part' list. You might also need to adjust the code to handle different Excel formats and edge cases.