تحويل الفئة المعرفة من قبل المستخدم إلى Excel

تحويل الصف المخصص للعميل إلى إكسل

في بعض الأحيان، لدينا مجموعة من الصفوف، وإذا أردنا استيراد معلومات الصف إلى ملف إكسل، فإن الحل المناسب هو استخدام آلية الانعكاس في Python لتضمين كل من بيانات الصف وأسماء متغيراته الأعضاء، بدون الحاجة لمعرفة بيانات الميتا الخاصة بالصف مسبقًا. إليك مثال لقطعة كود تشرح كيفية استيراد بيانات من قائمة الصفوف المخصصة للمستخدم إلى ملف إكسل باستخدام Aspose.Cells لـ Python via .NET: يعرف ملف 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")