簡體   English   中英

避免使用AttributeError:'set'對象沒有屬性'range'

[英]Avoid the AttributeError: 'set' object has no attribute 'ranges'

我想使用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開始,我仍然沒有好好關注這些錯誤

在你的代碼中, ws.merged_cells是一個set並且這個Object沒有任何范圍屬性,你可能會做類似的事情:

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

因為set()是空集對象

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM