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}") def extract_columns(self, filename, columns_to_extract, new_filename): """ Extracts specified columns from an existing Excel file and saves them to a new file. :param filename: The source Excel file name. :param columns_to_extract: A list of column indices (1-based) to extract. :param new_filename: The name of the new Excel file to save the extracted columns. """ # Load the source workbook source_wb = openpyxl.load_workbook(filename) source_sheet = source_wb.active # Create a new workbook and sheet new_wb = openpyxl.Workbook() new_sheet = new_wb.active # Copy headers for col_idx in columns_to_extract: new_sheet.cell(row=1, column=columns_to_extract.index(col_idx) + 1, value=source_sheet.cell(row=1, column=col_idx).value) # Copy data for row_idx, row in enumerate(source_sheet.iter_rows(min_row=2), start=2): for col_idx in columns_to_extract: new_sheet.cell(row=row_idx, column=columns_to_extract.index(col_idx) + 1, value=source_sheet.cell(row=row_idx, column=col_idx).value) # Save the new workbook new_wb.save(new_filename) print(f"Extracted columns saved to {new_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')