将自定义类转换为Excel

将自定义类转换为Excel

有时候,我们拥有一组类,如果想把类信息导入到Excel文件中,一个方便的解决方案是使用Python的反射机制,包含类数据和成员变量的名称,而无需预先知道类的具体元数据。 以下是一段示例代码,演示如何使用Aspose.Cells for Python via .NET将用户定义类列表中的数据导入Excel文件: 文件ImportCustomObject.py定义了要导入的类信息,并使用Python的反射机制,将类数据和成员变量名包含到特定单元格范围内。

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

文件TestImportCustomObject.py演示了一个简单示例。用户可以参考此示例或稍作修改以导入自己的数据。

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")