Convert Customer Defined Class to Excel
Convert Customer Defined Class to Excel
Sometimes, we have a collection of classes, and if we want to import class information into an Excel file, a convenient solution is to use Python’s reflection mechanism to include both the class data and the names of its member variables, without needing to know the class’s specific metadata in advance. Here’s an example code snippet demonstrating how to import data from a user-defined class list into an Excel file using Aspose.Cells for Python via .NET: The file ImportCustomObject.py defines the class information to be imported and uses Python’s reflection mechanism to include both the class data and member variable names into specific cell ranges.
from datetime import date, datetime | |
import aspose.cells as ac | |
class MyClass: | |
def __init__(self, Name, Age, Is_Student, Date, DateTime, Height): | |
self.Name = Name | |
self.Age = Age | |
self.Is_Student = Is_Student | |
self.Date = Date | |
self.DateTime = DateTime | |
self.Height = Height | |
def import_custom_object(people, cells, row, column, import_options): | |
# If a header needs to be displayed, write the header (attribute names) | |
if import_options.is_field_name_shown: | |
header = vars(people[0]).keys() | |
for col_index, attr_name in enumerate(header): | |
cells.get(row, column + col_index).put_value(attr_name) | |
row += 1 | |
# Write the attribute values of the object | |
for obj in people: | |
for col_index, (attr_name, attr_value) in enumerate(vars(obj).items()): | |
cell = cells.get(row, column + col_index) | |
if isinstance(attr_value, (int, float, str, bool)): | |
cell.put_value(attr_value) | |
elif isinstance(attr_value, (date, datetime)): | |
cell.put_value(attr_value) | |
style = cell.get_style() | |
if isinstance(attr_value, datetime): | |
style.custom = "yyyy-MM-dd HH:mm:ss" | |
elif isinstance(attr_value, date): | |
style.number = 14 # Excel Date Format | |
cell.set_style(style) | |
else: | |
cell.put_value(str(attr_value)) | |
row += 1 |
The file TestImportCustomObject.py illustrates a simple use case. Users can refer to this example or make slight modifications to import their own data.
from datetime import date, datetime | |
import aspose.cells as ac | |
from ImportCustomObject import MyClass, import_custom_object | |
people = [ | |
MyClass("Bob", 30, True, date(2024, 3, 9), datetime.now(), 112.0), | |
MyClass("Lucy", 25, False, date(2024, 3, 10), datetime.now(), 111.1), | |
MyClass("Tom", 45, True, date(2024, 3, 11), datetime.now(), 110.8), | |
] | |
workbook = ac.Workbook() | |
worksheet = workbook.worksheets[0] | |
cells = worksheet.cells | |
import_options = ac.ImportTableOptions() | |
# Display the table header or not | |
import_options.is_field_name_shown = True | |
start_row = 4 | |
start_column = 1 | |
import_custom_object(people, cells, start_row, start_column, import_options) | |
workbook.save("import_custom_object.xlsx") |