market_assistant/ExcelHelper.py

62 lines
2.3 KiB
Python

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