避免AttributeError:“ set”对象没有属性“ ranges”

时间:2019-04-30 16:08:36

标签: python openpyxl attributeerror

我想使用openpyxl编辑Excel电子表格。并取消合并文档中所有合并的单元格,以便更精确地读取整个工作表,然后将其保存在新文件中。以下是我正在使用的代码:

import os
import numpy as np
import pandas as pd
from openpyxl import load_workbook

base_folder = '/Users/esparaquia/Projects/readExcel'

test_file = 'BookTest.xlsm'
wb = load_workbook(filename=os.path.join(base_folder, test_file))
ws = wb['Sheet1']

# unmerge all the cells
while ws.merged_cells.ranges != []:
   # unmerge all the merged_cells
   for merged in ws.merged_cells.ranges:
      ws.unmerge_cells(str(merged))

# forward fill in every row based on border properties
value = ''
for irow, row in enumerate(ws.rows):

   # only worry about the first few rows (the headers)
   if irow < 2:

       for cell in row:
           # check if there is a left border (that it starts a header block)
           if multi_getattr(cell, 'border.left.color.tint') or cell.col_idx == 1:
              value = cell.value

           # fill in an empty space
           if cell.value is None or cell.value == '':
              cell.value = value

# save the modified file
temp_file = 'tmp.xlsx'
wb.save(filename=os.path.join(base_folder, temp_file))

这是我在运行此代码时遇到的错误:

---------------------------------------------------------------------------
AttributeError                  Traceback (most recent call last)
<ipython-input-15-96fa676a9b5d> in <module>()
      12 # unmerge all the cells
----> 13 while ws.merged_cells.ranges != []:
      14     # unmerge all the merged_cells
      15     for merged in ws.merged_cells.ranges:
      16         ws.unmerge_cells(str(merged))

AttributeError: 'set' object has no attribute 'ranges'

在此行:

while ws.merged_cells.ranges != []:

非常感谢您的帮助,我从Python开始,但仍然看不到这些错误

1 个答案:

答案 0 :(得分:0)

在您的代码中,ws.merged_cellsset,并且此Object不具有任何range属性,您可以执行类似的操作:

while ws.merged_cells.ranges != set():

因为set()是空的设置对象