鱼C论坛

 找回密码
 立即注册
查看: 1141|回复: 14

根据excel列数据提取模版,生成新的excel,有图片和格式的

[复制链接]
发表于 2024-7-26 14:13:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
目前已经提取了一个pandas的dataframe文件。
df_merge.to_excel("提取数据.xlsx", index=False)
同时生成到了excel,如下

管线号                                                             焊接类型        工艺卡编号        焊接材质        外径壁厚        管线寸口        道数        焊接寸口
/TRIM-排污-取样器水槽-N1-40-A1TB52-N             对焊                HKB20-02        20-GB/T8163        Φ48.3*5.08        1.5        1        1.5
/TRIM-排污-取样器水槽-N1-40-A1TB52-N            承插焊                HKC20-02        20-GB/T8163&20-NB/T47008        Φ*5.08        1.5        2        3
/TRIM-排污-取样器水槽-N1-40-A1TB52-N            承插焊                HKC20-02        20-GB/T8163&20-NB/T47008        Φ48.3*5.08        1.5        2        3
/TRIM-排污-取样器水槽-N1-40-A1TB52-N            承插焊                 HKC20-02        20-GB/T8163&A105        Φ*5.08        1.5        1        1.5
/TRIM-排污-取样器水槽-N1-40-A1TB52-N            承插焊                 HKC20-02        20-GB/T8163&A105        Φ48.3*5.08        1.5        1        1.5
/TRIM-排污-安全阀及消声器排水-20-A1TB51-N        承插焊        HKC20-02        20-GB/T8163        Φ21.3*3.73        1        7        7
/TRIM-排污-安全阀及消声器排水-20-A1TB51-N        对焊                HKB20-02        20-GB/T8163        Φ26.7*3.91        1        3        3

现在需要根据“管线号”列的数据,新建名称为“管线号”列数据的excel,并去同一级的另一个名称为“模版的文件夹里,找到”对应“工艺卡编号”列的名称的对应模版的excel,插入第一个sheet
sheet名称用“工艺卡编号“的名称

就是生成名称为“/TRIM-排污-取样器水槽-N1-40-A1TB52-N”.xlsx的excel,里面有模版sheet,名称为“HKB20-02”,“HKC20-02        ”,是复制“模版的文件夹里的对应模版的第一个sheet

提取模版能提取,但是模版里面有图,有格式,提取后图没了,excel表格式也没有全乱的,这个有没有其他办法
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2024-7-26 14:29:48 | 显示全部楼层
  1. import pandas as pd
  2. import os
  3. from openpyxl import load_workbook, Workbook

  4. # 假设你的 DataFrame 已经创建为 df_merge
  5. df_merge = pd.read_excel("提取数据2.xlsx")

  6. # 模板文件夹路径
  7. template_folder = "D:/PYTHON_NEW/pythonProject/提取python excel/工艺卡模版"
  8. # 定义输出路径
  9. output_folder = "C:\\集中"

  10. # 确保输出文件夹存在
  11. os.makedirs(output_folder, exist_ok=True)

  12. # 遍历每一行
  13. for index, row in df_merge.iterrows():
  14.           pipe_number = row['管线号']  # 假设管线号在 DataFrame 中的列名是 '管线号'

  15. # 创建新的 Excel 文件
  16.           new_file_path = os.path.join(output_folder, f"{pipe_number}.xlsx")
  17.           #new_file_path = os.path.join("E:\\JIESHOU",f"{pipe_number}.xlsx")
  18.           #new_file_path = os.path.join("E:\\JIESHOU",f"{pipe_number}.xlsx")
  19.           #new_file_path = os.path.join("C:\\33",f"{pipe_number}.xlsx")


  20. # 设置已存在的 Sheet 名称
  21.           existing_sheets = set()

  22. # 创建新的 Excel 工作簿
  23.           new_wb = Workbook()
  24. # 删除默认生成的第一个Sheet
  25.           default_sheet = new_wb.active
  26.           new_wb.remove(default_sheet)

  27. # 遍历与该管线号对应的所有工艺卡编号
  28.           for process_card in df_merge.loc[df_merge['管线号'] == pipe_number, '工艺卡编号'].unique():
  29.                           template_path = os.path.join(template_folder, f"{process_card}.xlsx")

  30.                           if os.path.exists(template_path):
  31.                                     wb_template = load_workbook(template_path)
  32.                                     sheet_name = process_card

  33. # 确保 Sheet 名称唯一
  34.                                     suffix = 1
  35.                                     while sheet_name in existing_sheets:
  36.                                               sheet_name = f"{process_card}_{suffix}"
  37.                                               suffix += 1

  38. # 获取模版的第一个sheet
  39.                                     template_sheet = wb_template.active

  40. # 创建一个新的工作表
  41.                                     new_sheet = new_wb.create_sheet(title=sheet_name)

  42.                                     # 复制数据
  43.                                     for row in template_sheet.iter_rows(values_only=True):
  44.                                            # new_sheet.append(row)   # 将每一行的数据添加到新的工作表中
  45.                                            for cell in row:
  46.                                                new_sheet[cell.coordinate].value = cell.value
  47.                                                if cell.has_style:
  48.                                                    new_sheet[cell.coordinate].font = cell.font
  49.                                                    new_sheet[cell.coordinate].border = cell.border
  50.                                                    new_sheet[cell.coordinate].fill = cell.fill
  51.                                                    new_sheet[cell.coordinate].number_format = cell.number_format
  52.                                                    new_sheet[cell.coordinate].protection = cell.protection
  53.                                                    new_sheet[cell.coordinate].alignment = cell.alignment

  54.                                                # 复制图片
  55.                                     for img in template_sheet._images:
  56.                                             new_sheet.add_image(img)




  57.                                     existing_sheets.add(sheet_name)
  58.                           else:
  59.                                     print(f"模板文件 {process_card}.xlsx 不存在,请检查路径!")

  60. # 保存新文件
  61.           new_wb.save(new_file_path)
  62.           print(f"已创建: {new_file_path} 包含模版: {existing_sheets}")

  63. print("所有文件处理完成!")
复制代码


程序报错
D:\PYTHON_NEW\pythonProject\.venv\Scripts\python.exe "D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py"
Traceback (most recent call last):
  File "D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py", line 60, in <module>
    new_sheet[cell.coordinate].value = cell.value
                                       ^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'value'
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-26 14:37:45 | 显示全部楼层
  1. import pandas as pd
  2. import os
  3. from openpyxl import load_workbook, Workbook

  4. # 假设你的 DataFrame 已经创建为 df_merge
  5. df_merge = pd.read_excel("提取数据2.xlsx")

  6. # 模板文件夹路径
  7. template_folder = "D:/PYTHON_NEW/pythonProject/提取python excel/工艺卡模版"
  8. # 定义输出路径
  9. output_folder = "C:\\集中"

  10. # 确保输出文件夹存在
  11. os.makedirs(output_folder, exist_ok=True)

  12. # 遍历每一行
  13. for index, row in df_merge.iterrows():
  14.           pipe_number = row['管线号']  # 假设管线号在 DataFrame 中的列名是 '管线号'

  15. # 创建新的 Excel 文件
  16.           new_file_path = os.path.join(output_folder, f"{pipe_number}.xlsx")
  17.           #new_file_path = os.path.join("E:\\JIESHOU",f"{pipe_number}.xlsx")
  18.           #new_file_path = os.path.join("E:\\JIESHOU",f"{pipe_number}.xlsx")
  19.           #new_file_path = os.path.join("C:\\33",f"{pipe_number}.xlsx")


  20. # 设置已存在的 Sheet 名称
  21.           existing_sheets = set()

  22. # 创建新的 Excel 工作簿
  23.           new_wb = Workbook()
  24. # 删除默认生成的第一个Sheet
  25.           default_sheet = new_wb.active
  26.           new_wb.remove(default_sheet)

  27. # 遍历与该管线号对应的所有工艺卡编号
  28.           for process_card in df_merge.loc[df_merge['管线号'] == pipe_number, '工艺卡编号'].unique():
  29.                           template_path = os.path.join(template_folder, f"{process_card}.xlsx")

  30.                           if os.path.exists(template_path):
  31.                                     wb_template = load_workbook(template_path)
  32.                                     sheet_name = process_card

  33. # 确保 Sheet 名称唯一
  34.                                     suffix = 1
  35.                                     while sheet_name in existing_sheets:
  36.                                               sheet_name = f"{process_card}_{suffix}"
  37.                                               suffix += 1

  38. # 获取模版的第一个sheet
  39.                                     template_sheet = wb_template.active

  40. # 创建一个新的工作表
  41.                                     new_sheet = new_wb.create_sheet(title=sheet_name)

  42.                                     # 复制数据
  43.                                     for i, row in enumerate(template_sheet.iter_rows(values_only=False)):
  44.                                         for j, cell in enumerate(row):
  45.                                             new_cell = new_sheet.cell(row=i + 1, column=j + 1, value=cell.value)
  46.                                             if cell.has_style:
  47.                                                 new_cell.font = cell.font
  48.                                                 new_cell.border = cell.border
  49.                                                 new_cell.fill = cell.fill
  50.                                                 new_cell.number_format = cell.number_format
  51.                                                 new_cell.protection = cell.protection
  52.                                                 new_cell.alignment = cell.alignment

  53.                                     # 复制图片
  54.                                     for img in template_sheet._images:
  55.                                         new_sheet.add_image(img)
  56.                                     existing_sheets.add(sheet_name)
  57.                           else:
  58.                                     print(f"模板文件 {process_card}.xlsx 不存在,请检查路径!")

  59. # 保存新文件
  60.           new_wb.save(new_file_path)
  61.           print(f"已创建: {new_file_path} 包含模版: {existing_sheets}")

  62. print("所有文件处理完成!")
复制代码


报错如下,
D:\PYTHON_NEW\pythonProject\.venv\Scripts\python.exe "D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py"
Traceback (most recent call last):
  File "D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py", line 61, in <module>
    new_cell.font = cell.font
    ^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\openpyxl\styles\styleable.py", line 27, in __set__
    setattr(instance._style, self.key, coll.add(value))
                                       ^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\openpyxl\utils\indexed_list.py", line 48, in add
    self.append(value)
  File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\openpyxl\utils\indexed_list.py", line 43, in append
    if value not in self._dict:
       ^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'StyleProxy'

Process finished with exit code 1
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-26 14:42:30 | 显示全部楼层
  1. import pandas as pd
  2. import os
  3. from openpyxl import load_workbook, Workbook

  4. # 假设你的 DataFrame 已经创建为 df_merge
  5. df_merge = pd.read_excel("提取数据2.xlsx")

  6. 报错如下
  7. D:\PYTHON_NEW\pythonProject\.venv\Scripts\python.exe "D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py"
  8. D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py:61: DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
  9.   new_cell.font = cell.font.copy() if cell.font else None
  10. D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py:62: DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
  11.   new_cell.border = cell.border.copy() if cell.border else None
  12. D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py:63: DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
  13.   new_cell.fill = cell.fill.copy() if cell.fill else None
  14. D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py:65: DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
  15.   new_cell.protection = cell.protection.copy() if cell.protection else None
  16. D:\PYTHON_NEW\pythonProject\提取python excel\可用 抽出工艺卡片.py:66: DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
  17.   new_cell.alignment = cell.alignment.copy() if cell.alignment else None
  18. 已创建: C:/TRIM-排污-取样器水槽-N1-40-A1TB52-N.xlsx 包含模版: {'HKB12-02', 'HKB12-03'}
  19. 已创建: C:/TRIM-排污-取样器水槽-N1-40-A1TB52-N.xlsx 包含模版: {'HKB12-02', 'HKB12-03'}
  20. 已创建: C:/TRIM-排污-取样器水槽-N1-40-A1TB52-N.xlsx 包含模版: {'HKB12-02', 'HKB12-03'}
  21. 已创建: C:/TRIM-排污-取样器水槽-N1-40-A1TB52-N.xlsx 包含模版: {'HKB12-02', 'HKB12-03'}
  22. 已创建: C:/TRIM-排污-取样器水槽-N1-40-A1TB52-N.xlsx 包含模版: {'HKB12-02', 'HKB12-03'}
  23. 已创建: C:/TRIM-排污-安全阀及消声器排水-20-A1TB51-N.xlsx 包含模版: {'HKB12-02'}
  24. 已创建: C:/TRIM-排污-安全阀及消声器排水-20-A1TB51-N.xlsx 包含模版: {'HKB12-02'}
  25. 已创建: C:/TRIM-排污-安全阀及消声器排水-20-A1TB51-N.xlsx 包含模版: {'HKB12-02'}
  26. 已创建: C:/TRIM-GG.xlsx 包含模版: {'HKB12-02'}
  27. 已创建: C:/TRIM-CC.xlsx 包含模版: {'HKB12-01'}
  28. 已创建: C:/TRIM-BB.xlsx 包含模版: {'HKB12-02'}
  29. 已创建: C:/TRIM-BB.xlsx 包含模版: {'HKB12-02'}
  30. 所有文件处理完成!

  31. Process finished with exit code 0


  32. # 模板文件夹路径
  33. template_folder = "D:/PYTHON_NEW/pythonProject/提取python excel/工艺卡模版"
  34. # 定义输出路径
  35. output_folder = "C:\\集中"

  36. # 确保输出文件夹存在
  37. os.makedirs(output_folder, exist_ok=True)

  38. # 遍历每一行
  39. for index, row in df_merge.iterrows():
  40.           pipe_number = row['管线号']  # 假设管线号在 DataFrame 中的列名是 '管线号'

  41. # 创建新的 Excel 文件
  42.           new_file_path = os.path.join(output_folder, f"{pipe_number}.xlsx")
  43.           #new_file_path = os.path.join("E:\\JIESHOU",f"{pipe_number}.xlsx")
  44.           #new_file_path = os.path.join("E:\\JIESHOU",f"{pipe_number}.xlsx")
  45.           #new_file_path = os.path.join("C:\\33",f"{pipe_number}.xlsx")


  46. # 设置已存在的 Sheet 名称
  47.           existing_sheets = set()

  48. # 创建新的 Excel 工作簿
  49.           new_wb = Workbook()
  50. # 删除默认生成的第一个Sheet
  51.           default_sheet = new_wb.active
  52.           new_wb.remove(default_sheet)

  53. # 遍历与该管线号对应的所有工艺卡编号
  54.           for process_card in df_merge.loc[df_merge['管线号'] == pipe_number, '工艺卡编号'].unique():
  55.                           template_path = os.path.join(template_folder, f"{process_card}.xlsx")

  56.                           if os.path.exists(template_path):
  57.                                     wb_template = load_workbook(template_path)
  58.                                     sheet_name = process_card

  59. # 确保 Sheet 名称唯一
  60.                                     suffix = 1
  61.                                     while sheet_name in existing_sheets:
  62.                                               sheet_name = f"{process_card}_{suffix}"
  63.                                               suffix += 1

  64. # 获取模版的第一个sheet
  65.                                     template_sheet = wb_template.active

  66. # 创建一个新的工作表
  67.                                     new_sheet = new_wb.create_sheet(title=sheet_name)

  68.                                     # 复制数据
  69.                                     for i, row in enumerate(template_sheet.iter_rows(values_only=False)):
  70.                                         for j, cell in enumerate(row):
  71.                                             new_cell = new_sheet.cell(row=i + 1, column=j + 1, value=cell.value)
  72.                                             if cell.has_style:
  73.                                                 new_cell.font = cell.font.copy() if cell.font else None
  74.                                                 new_cell.border = cell.border.copy() if cell.border else None
  75.                                                 new_cell.fill = cell.fill.copy() if cell.fill else None
  76.                                                 new_cell.number_format = cell.number_format
  77.                                                 new_cell.protection = cell.protection.copy() if cell.protection else None
  78.                                                 new_cell.alignment = cell.alignment.copy() if cell.alignment else None

  79.                                     # 复制图片
  80.                                     for img in template_sheet._images:
  81.                                         new_sheet.add_image(img)
  82.                                     existing_sheets.add(sheet_name)
  83.                           else:
  84.                                     print(f"模板文件 {process_card}.xlsx 不存在,请检查路径!")

  85. # 保存新文件
  86.           new_wb.save(new_file_path)
  87.           print(f"已创建: {new_file_path} 包含模版: {existing_sheets}")

  88. print("所有文件处理完成!")
复制代码

能抽出数据,但是图片没抽出来的,单元格格式也不对
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-26 14:45:05 | 显示全部楼层
主要是合并,对齐,行高这些都不对
图片没拉过去
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-26 14:49:58 | 显示全部楼层
  1. # Copyright (c) 2010-2024 openpyxl

  2. from copy import copy
  3. from warnings import warn

  4. from .numbers import (
  5.     BUILTIN_FORMATS,
  6.     BUILTIN_FORMATS_MAX_SIZE,
  7.     BUILTIN_FORMATS_REVERSE,
  8. )
  9. from .proxy import StyleProxy
  10. from .cell_style import StyleArray
  11. from .named_styles import NamedStyle
  12. from .builtins import styles


  13. class StyleDescriptor(object):

  14.     def __init__(self, collection, key):
  15.         self.collection = collection
  16.         self.key = key

  17.     def __set__(self, instance, value):
  18.         coll = getattr(instance.parent.parent, self.collection)
  19.         if not getattr(instance, "_style"):
  20.             instance._style = StyleArray()
  21.         setattr(instance._style, self.key, coll.add(value))


  22.     def __get__(self, instance, cls):
  23.         coll = getattr(instance.parent.parent, self.collection)
  24.         if not getattr(instance, "_style"):
  25.             instance._style = StyleArray()
  26.         idx =  getattr(instance._style, self.key)
  27.         return StyleProxy(coll[idx])


  28. class NumberFormatDescriptor(object):

  29.     key = "numFmtId"
  30.     collection = '_number_formats'

  31.     def __set__(self, instance, value):
  32.         coll = getattr(instance.parent.parent, self.collection)
  33.         if value in BUILTIN_FORMATS_REVERSE:
  34.             idx = BUILTIN_FORMATS_REVERSE[value]
  35.         else:
  36.             idx = coll.add(value) + BUILTIN_FORMATS_MAX_SIZE

  37.         if not getattr(instance, "_style"):
  38.             instance._style = StyleArray()
  39.         setattr(instance._style, self.key, idx)


  40.     def __get__(self, instance, cls):
  41.         if not getattr(instance, "_style"):
  42.             instance._style = StyleArray()
  43.         idx = getattr(instance._style, self.key)
  44.         if idx < BUILTIN_FORMATS_MAX_SIZE:
  45.             return BUILTIN_FORMATS.get(idx, "General")
  46.         coll = getattr(instance.parent.parent, self.collection)
  47.         return coll[idx - BUILTIN_FORMATS_MAX_SIZE]


  48. class NamedStyleDescriptor(object):

  49.     key = "xfId"
  50.     collection = "_named_styles"


  51.     def __set__(self, instance, value):
  52.         if not getattr(instance, "_style"):
  53.             instance._style = StyleArray()
  54.         coll = getattr(instance.parent.parent, self.collection)
  55.         if isinstance(value, NamedStyle):
  56.             style = value
  57.             if style not in coll:
  58.                 instance.parent.parent.add_named_style(style)
  59.         elif value not in coll.names:
  60.             if value in styles: # is it builtin?
  61.                 style = styles[value]
  62.                 if style not in coll:
  63.                     instance.parent.parent.add_named_style(style)
  64.             else:
  65.                 raise ValueError("{0} is not a known style".format(value))
  66.         else:
  67.             style = coll[value]
  68.         instance._style = copy(style.as_tuple())


  69.     def __get__(self, instance, cls):
  70.         if not getattr(instance, "_style"):
  71.             instance._style = StyleArray()
  72.         idx = getattr(instance._style, self.key)
  73.         coll = getattr(instance.parent.parent, self.collection)
  74.         return coll.names[idx]


  75. class StyleArrayDescriptor(object):

  76.     def __init__(self, key):
  77.         self.key = key

  78.     def __set__(self, instance, value):
  79.         if instance._style is None:
  80.             instance._style = StyleArray()
  81.         setattr(instance._style, self.key, value)


  82.     def __get__(self, instance, cls):
  83.         if instance._style is None:
  84.             return False
  85.         return bool(getattr(instance._style, self.key))


  86. class StyleableObject(object):
  87.     """
  88.     Base class for styleble objects implementing proxy and lookup functions
  89.     """

  90.     font = StyleDescriptor('_fonts', "fontId")
  91.     fill = StyleDescriptor('_fills', "fillId")
  92.     border = StyleDescriptor('_borders', "borderId")
  93.     number_format = NumberFormatDescriptor()
  94.     protection = StyleDescriptor('_protections', "protectionId")
  95.     alignment = StyleDescriptor('_alignments', "alignmentId")
  96.     style = NamedStyleDescriptor()
  97.     quotePrefix = StyleArrayDescriptor('quotePrefix')
  98.     pivotButton = StyleArrayDescriptor('pivotButton')

  99.     __slots__ = ('parent', '_style')

  100.     def __init__(self, sheet, style_array=None):
  101.         self.parent = sheet
  102.         if style_array is not None:
  103.             style_array = StyleArray(style_array)
  104.         self._style = style_array


  105.     @property
  106.     def style_id(self):
  107.         if self._style is None:
  108.             self._style = StyleArray()
  109.         return self.parent.parent._cell_styles.add(self._style)


  110.     @property
  111.     def has_style(self):
  112.         if self._style is None:
  113.             return False
  114.         return any(self._style)

复制代码


失败了,报错如下
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 59, in <module>
    new_cell.font = cell.font
    ^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\openpyxl\styles\styleable.py", line 27, in __set__
    setattr(instance._style, self.key, coll.add(value))
                                       ^^^^^^^^^^^^^^^
  File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\openpyxl\utils\indexed_list.py", line 48, in add
    self.append(value)
  File "D:\PYTHON_NEW\pythonProject\.venv\Lib\site-packages\openpyxl\utils\indexed_list.py", line 43, in append
    if value not in self._dict:
       ^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'StyleProxy'

Process finished with exit code 1
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-26 14:52:48 | 显示全部楼层
  1. import pandas as pd
  2. import os
  3. from openpyxl import load_workbook, Workbook

  4. # 假设你的 DataFrame 已经创建为 df_merge
  5. df_merge = pd.read_excel("提取数据2.xlsx")

  6. # 模板文件夹路径
  7. template_folder = "D:/PYTHON_NEW/pythonProject/提取python excel/工艺卡模版"
  8. # 定义输出路径
  9. output_folder = "C:\\集中"

  10. # 确保输出文件夹存在
  11. os.makedirs(output_folder, exist_ok=True)

  12. # 遍历每一行
  13. for index, row in df_merge.iterrows():
  14.     pipe_number = row['管线号']  # 假设管线号在 DataFrame 中的列名是 '管线号'

  15.     # 创建新的 Excel 文件
  16.     new_file_path = os.path.join(output_folder, f"{pipe_number}.xlsx")

  17.     # 设置已存在的 Sheet 名称
  18.     existing_sheets = set()

  19.     # 创建新的 Excel 工作簿
  20.     new_wb = Workbook()
  21.     # 删除默认生成的第一个Sheet
  22.     default_sheet = new_wb.active
  23.     new_wb.remove(default_sheet)

  24.     # 遍历与该管线号对应的所有工艺卡编号
  25.     for process_card in df_merge.loc[df_merge == pipe_number, '工艺卡编号'].unique():
  26.         template_path = os.path.join(template_folder, f"{process_card}.xlsx")

  27.         if os.path.exists(template_path):
  28.             wb_template = load_workbook(template_path)
  29.             sheet_name = process_card

  30.             # 确保 Sheet 名称唯一
  31.             suffix = 1
  32.             while sheet_name in existing_sheets:
  33.                 sheet_name = f"{process_card}_{suffix}"
  34.                 suffix += 1

  35.             # 获取模版的第一个sheet
  36.             template_sheet = wb_template.active
  37.             new_sheet = new_wb.create_sheet(title=sheet_name)

  38.             # 复制数据和样式
  39.             for i, row in enumerate(template_sheet.iter_rows(values_only=False)):
  40.                 for j, cell in enumerate(row):
  41.                     new_cell = new_sheet.cell(row=i + 1, column=j + 1, value=cell.value)

  42.                     # 复制样式属性
  43.                     if cell.has_style:
  44.                         if cell.font is not None:
  45.                             new_cell.font = cell.font
  46.                         if cell.border is not None:
  47.                             new_cell.border = cell.border
  48.                         if cell.fill is not None:
  49.                             new_cell.fill = cell.fill
  50.                         new_cell.number_format = cell.number_format
  51.                         new_cell.protection = cell.protection
  52.                         if cell.alignment is not None:
  53.                             new_cell.alignment = cell.alignment

  54.             # 复制行高
  55.             for row in template_sheet.iter_rows():
  56.                 new_sheet.row_dimensions[row[0].row].height = row[0].row_height

  57.             # 复制合并单元格
  58.             for merged_range in template_sheet.merged_cells.ranges:
  59.                 new_sheet.merge_cells(str(merged_range))

  60.             # 复制图片
  61.             for img in template_sheet._images:
  62.                 new_sheet.add_image(img)

  63.             existing_sheets.add(sheet_name)
  64.         else:
  65.             print(f"模板文件 {process_card}.xlsx 不存在,请检查路径!")

  66.     # 保存新文件
  67.     new_wb.save(new_file_path)
  68.     print(f"已创建: {new_file_path} 包含模版: {existing_sheets}")

  69. 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
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-26 15:06:03 | 显示全部楼层
  1. import pandas as pd
  2. import os
  3. from openpyxl import load_workbook, Workbook

  4. # 假设你的 DataFrame 已经创建为 df_merge
  5. df_merge = pd.read_excel("提取数据2.xlsx")

  6. # 模板文件夹路径
  7. template_folder = "D:/PYTHON_NEW/pythonProject/提取python excel/工艺卡模版"
  8. # 定义输出路径
  9. output_folder = "C:\\集中"

  10. # 确保输出文件夹存在
  11. os.makedirs(output_folder, exist_ok=True)

  12. # 遍历每一行
  13. for index, row in df_merge.iterrows():
  14.           pipe_number = row['管线号']    # 假设管线号在 DataFrame 中的列名是 '管线号'

  15. # 创建新的 Excel 文件
  16.           new_file_path = os.path.join(output_folder, f"{pipe_number}.xlsx")

  17. # 设置已存在的 Sheet 名称
  18.           existing_sheets = set()

  19. # 创建新的 Excel 工作簿
  20.           new_wb = Workbook()
  21. # 删除默认生成的第一个Sheet
  22.           default_sheet = new_wb.active
  23.           new_wb.remove(default_sheet)

  24. # 遍历与该管线号对应的所有工艺卡编号
  25.           for process_card in df_merge.loc[df_merge == pipe_number, '工艺卡编号'].unique():
  26.                  template_path = os.path.join(template_folder, f"{process_card}.xlsx")

  27.                  if os.path.exists(template_path):
  28.                                     wb_template = load_workbook(template_path)
  29.                                     sheet_name = process_card

  30. # 确保 Sheet 名称唯一
  31.                                     suffix = 1
  32.                                     while sheet_name in existing_sheets:
  33.                                               sheet_name = f"{process_card}_{suffix}"
  34.                                               suffix += 1

  35. # 获取模版的第一个sheet
  36.                                     template_sheet = wb_template.active
  37.                                     new_sheet = new_wb.create_sheet(title=sheet_name)

  38. # 复制数据和样式
  39.                                     for i, row in enumerate(template_sheet.iter_rows(values_only=False)):
  40.                                             for j, cell in enumerate(row):
  41.                                                              new_cell = new_sheet.cell(row=i + 1, column=j + 1, value=cell.value)

  42. # 复制样式属性
  43.                                                              if cell.has_style:
  44.                                                                         if cell.font is not None:
  45.                                                                             new_cell.font = cell.font
  46.                                                                         if cell.border is not None:
  47.                                                                             new_cell.border = cell.border
  48.                                                                         if cell.fill is not None:
  49.                                                                             new_cell.fill = cell.fill
  50.                                                                         new_cell.number_format = cell.number_format
  51.                                                                         new_cell.protection = cell.protection
  52.                                                                         if cell.alignment is not None:
  53.                                                                             new_cell.alignment = cell.alignment

  54. # 复制行高
  55.                                     for row in template_sheet.iter_rows():
  56.                                               new_sheet.row_dimensions[row[0].row].height = row[0].row_height

  57. # 复制合并单元格
  58.                                     for merged_range in template_sheet.merged_cells.ranges:
  59.                                               new_sheet.merge_cells(str(merged_range))

  60. # 复制图片
  61.                                     for img in template_sheet._images:
  62.                                               new_sheet.add_image(img)

  63.                                     existing_sheets.add(sheet_name)
  64.                  else:
  65.                                     print(f"模板文件 {process_card}.xlsx 不存在,请检查路径!")

  66. # 保存新文件
  67. new_wb.save(new_file_path)
  68. print(f"已创建: {new_file_path} 包含模版: {existing_sheets}")

  69. print("所有文件处理完成!")
复制代码


AI老师能不能发的代码可以直接复制不用调缩进的。。。
失败如下
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
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-7-26 15:07:49 | 显示全部楼层
  1. import pandas as pd
  2. import os
  3. from openpyxl import load_workbook, Workbook

  4. # 假设你的 DataFrame 已经创建为 df_merge
  5. df_merge = pd.read_excel("提取数据2.xlsx")

  6. # 模板文件夹路径
  7. template_folder = "D:/PYTHON_NEW/pythonProject/提取python excel/工艺卡模版"
  8. # 定义输出路径
  9. output_folder = "C:\\集中"

  10. # 确保输出文件夹存在
  11. os.makedirs(output_folder, exist_ok=True)

  12. # 遍历每一行
  13. for index, row in df_merge.iterrows():
  14.     pipe_number = row['管线号']  # 假设管线号在 DataFrame 中的列名是 '管线号'

  15.     # 创建新的 Excel 文件
  16.     new_file_path = os.path.join(output_folder, f"{pipe_number}.xlsx")

  17.     # 设置已存在的 Sheet 名称
  18.     existing_sheets = set()

  19.     # 创建新的 Excel 工作簿
  20.     new_wb = Workbook()
  21.     # 删除默认生成的第一个Sheet
  22.     default_sheet = new_wb.active
  23.     new_wb.remove(default_sheet)

  24.     # 遍历与该管线号对应的所有工艺卡编号
  25.     for process_card in df_merge.loc[df_merge == pipe_number, '工艺卡编号'].unique():
  26.         template_path = os.path.join(template_folder, f"{process_card}.xlsx")

  27.         if os.path.exists(template_path):
  28.             wb_template = load_workbook(template_path)
  29.             sheet_name = process_card

  30.             # 确保 Sheet 名称唯一
  31.             suffix = 1
  32.             while sheet_name in existing_sheets:
  33.                 sheet_name = f"{process_card}_{suffix}"
  34.                 suffix += 1

  35.             # 获取模版的第一个sheet
  36.             template_sheet = wb_template.active
  37.             new_sheet = new_wb.create_sheet(title=sheet_name)

  38.             # 复制数据和样式
  39.             for i, row in enumerate(template_sheet.iter_rows(values_only=False)):
  40.                 for j, cell in enumerate(row):
  41.                     new_cell = new_sheet.cell(row=i + 1, column=j + 1, value=cell.value)

  42.                     # 复制样式属性
  43.                     if cell.has_style:
  44.                         if cell.font is not None:
  45.                             new_cell.font = cell.font
  46.                         if cell.border is not None:
  47.                             new_cell.border = cell.border
  48.                         if cell.fill is not None:
  49.                             new_cell.fill = cell.fill
  50.                         new_cell.number_format = cell.number_format
  51.                         new_cell.protection = cell.protection
  52.                         if cell.alignment is not None:
  53.                             new_cell.alignment = cell.alignment

  54.             # 复制行高
  55.             for row in template_sheet.iter_rows():
  56.                 new_sheet.row_dimensions[row[0].row].height = row[0].row_height

  57.             # 复制合并单元格
  58.             for merged_range in template_sheet.merged_cells.ranges:
  59.                 new_sheet.merge_cells(str(merged_range))

  60.             # 复制图片
  61.             for img in template_sheet._images:
  62.                 new_sheet.add_image(img)

  63.             existing_sheets.add(sheet_name)
  64.         else:
  65.             print(f"模板文件 {process_card}.xlsx 不存在,请检查路径!")

  66.     # 保存新文件
  67.     new_wb.save(new_file_path)
  68.     print(f"已创建: {new_file_path} 包含模版: {existing_sheets}")

  69. 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
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-7 03:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表