カスタム定義クラスを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") |