马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pandas as pd
import os
from openpyxl import load_workbook, Workbook
# 假设你的 DataFrame 已经创建为 df_merge
df_merge = pd.read_excel("提取数据2.xlsx")
# 模板文件夹路径
template_folder = "D:/PYTHON_NEW/pythonProject/提取python excel/工艺卡模版"
# 定义输出路径
output_folder = "C:\\集中"
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=True)
# 遍历每一行
for index, row in df_merge.iterrows():
pipe_number = row['管线号'] # 假设管线号在 DataFrame 中的列名是 '管线号'
# 创建新的 Excel 文件
new_file_path = os.path.join(output_folder, f"{pipe_number}.xlsx")
# 设置已存在的 Sheet 名称
existing_sheets = set()
# 创建新的 Excel 工作簿
new_wb = Workbook()
# 删除默认生成的第一个Sheet
default_sheet = new_wb.active
new_wb.remove(default_sheet)
# 遍历与该管线号对应的所有工艺卡编号
for process_card in df_merge.loc[df_merge == pipe_number, '工艺卡编号'].unique():
template_path = os.path.join(template_folder, f"{process_card}.xlsx")
if os.path.exists(template_path):
wb_template = load_workbook(template_path)
sheet_name = process_card
# 确保 Sheet 名称唯一
suffix = 1
while sheet_name in existing_sheets:
sheet_name = f"{process_card}_{suffix}"
suffix += 1
# 获取模版的第一个sheet
template_sheet = wb_template.active
new_sheet = new_wb.create_sheet(title=sheet_name)
# 复制数据和样式
for i, row in enumerate(template_sheet.iter_rows(values_only=False)):
for j, cell in enumerate(row):
new_cell = new_sheet.cell(row=i + 1, column=j + 1, value=cell.value)
# 复制样式属性
if cell.has_style:
if cell.font is not None:
new_cell.font = cell.font
if cell.border is not None:
new_cell.border = cell.border
if cell.fill is not None:
new_cell.fill = cell.fill
new_cell.number_format = cell.number_format
new_cell.protection = cell.protection
if cell.alignment is not None:
new_cell.alignment = cell.alignment
# 复制行高
for row in template_sheet.iter_rows():
new_sheet.row_dimensions[row[0].row].height = row[0].row_height
# 复制合并单元格
for merged_range in template_sheet.merged_cells.ranges:
new_sheet.merge_cells(str(merged_range))
# 复制图片
for img in template_sheet._images:
new_sheet.add_image(img)
existing_sheets.add(sheet_name)
else:
print(f"模板文件 {process_card}.xlsx 不存在,请检查路径!")
# 保存新文件
new_wb.save(new_file_path)
print(f"已创建: {new_file_path} 包含模版: {existing_sheets}")
print("所有文件处理完成!")
代码报错如下
D:\PYTHON_NEW\pythonProject\.venv\Scripts\python.exe "D:\PYTHON_NEW\pythonProject\提取python excel\测试含图片的excel抽取工艺卡.py"
Traceback (most recent call last):
File "D:\PYTHON_NEW\pythonProject\提取python excel\测试含图片的excel抽取工艺卡.py", line 33, in <module>
for process_card in df_merge.loc[df_merge == pipe_number, '工艺卡编号'].unique():
~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\pandas\core\indexing.py", line 1184, in __getitem__
return self._getitem_tuple(key)
^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\pandas\core\indexing.py", line 1368, in _getitem_tuple
return self._getitem_lowerdim(tup)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\pandas\core\indexing.py", line 1089, in _getitem_lowerdim
return getattr(section, self.name)[new_key]
~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^
File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\pandas\core\indexing.py", line 1191, in __getitem__
return self._getitem_axis(maybe_callable, axis=axis)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\pandas\core\indexing.py", line 1418, in _getitem_axis
raise ValueError("Cannot index with multidimensional key")
ValueError: Cannot index with multidimensional key
Process finished with exit code 1
老师帮看下,太长了,吓人
|