2017-09-26 123 views
0

所以,我在每個excel文件中都放了幾張紙,而且我正在處理腳本,它將從所選工作表收集數據(如果它們存在於文件中並將其合併到一個大單中) 。一般來說,它正在工作,遍歷文件,如果需要的工作表存在,它會找到包含數據的單元格區域並將其附加到數據框。我現在需要做的事情是將標題行(列名稱)添加到Dataframe,但在表格中是多行標題。openPyXL - 在取消合併期間爲單元格範圍分配值

爲了使它在數據框中看起來相同,我需要在頂部標題行中取消合併單元格,並將第一個單元格的值複製到之前合併的範圍中的其餘部分。

我使用OpenPyXL訪問Excel表。我的函數接收工作表作爲唯一參數。它看起來像這樣:

def checkForMergedCells(sheet): 
    merged = ws.merged_cell_ranges 
    for mergedCell in merged: 
     mc_start, mc_stop = str(mergedCell).split(':') 
     cp_value = sheet[mc_start] 
     sheet.unmerge_cells(mergedCell) 
     cell_range = sheet[mergedCell] 
     for cell in cell_range: 
      cell.value = cp_value 

的事情是,CELL_RANGE返回其在收到錯誤消息,結束了一個元組:

AttributeError: 'tuple' object has no attribute 'value' Below you can see screencap during debug which shows values passed in each variable.

Debugger running

回答

1

訪問由指數一般會返回一個元組的元組除非您嘗試獲取單個單元格或行。對於編程式訪問,您應該使用iter_rows()iter_cols()

您可能想花一些時間查看utils模塊。

from openpyxl.utils import range_boundaries 

for group in ws.merged_cell_ranges: 
    min_col, min_row, max_col, max_row = range_boundaries(group) 
    top_left_cell_value = ws.cell(row=min_row, column=min_col).value 
    for row in ws.iter_rows(min_col=min_col, min_row=min_row, max_col=max_col, max_row=max_row): 
     for cell in row: 
      cell.value = top_left_cell_value 
相關問題