import openpyxl from openpyxl.styles import Font class ExcelHelper: def __init__(self, data): """ 初始化 ExcelHelper 实例 :param data: 包含多个数组的列表,每个数组包含字典,每个字典有 'title' 和 'content' 键 """ self.data = data self.workbook = openpyxl.Workbook() self.sheet = self.workbook.active def create_excel(self, filename): """ 创建 Excel 文件并保存 :param filename: 保存的文件名 """ start_row = 1 for array in self.data: col = 1 for item in array: self.sheet.cell(row=start_row, column=col, value=item['title']).font = Font(bold=True) self.sheet.cell(row=start_row + 1, column=col, value=item['content']) col += 1 # 在每个数组之间添加两行空行 start_row += 3 self.workbook.save(filename) print(f"Excel 文件已保存为 {filename}") # # 示例数据 # data = [ # [ # {'title': 'Title 1', 'content': 'Content 1'}, # {'title': 'Title 2', 'content': 'Content 2'}, # {'title': 'Title 3', 'content': 'Content 3'} # ], # [ # {'title': 'Title 4', 'content': 'Content 4'}, # {'title': 'Title 5', 'content': 'Content 5'}, # {'title': 'Title 6', 'content': 'Content 6'} # ] # ] # # 创建 ExcelHelper 实例并生成 Excel 文件 # excel_helper = ExcelHelper(data) # excel_helper.create_excel('output.xlsx')