如何在Python中跳过几行Excel表格

问题描述 投票:2回答:2

我能够使用openpyxl成功地合并Excel表格中的所有单元格;但是,我想保持表格的前7行完好无损。如下所示,前7行包含合并的单元格。

Upper excel sheet

在我运行以下代码(找到合并的单元格并拆分它们)之后:

def fill_in(rows,first_cell,last_cell):
    #Take first cell's value
    first_value = first_cell.value
    #Copy and fill/assign this value into each cell of the range
    for tmp in rows:  
        cell = tmp[0]
        print(cell) ##E.g. (<Cell 'Sheet1'.A1>,)  
        print(cell.value) ##E.g. Order Records
        cell.value = first_value 

wb2 = load_workbook('Example.xlsx')
sheets = wb2.sheetnames ##list of sheetnames
for i,sheet in enumerate(sheets): ##for each sheet
    ws = wb2[sheets[i]]
    range_list = ws.merged_cell_ranges
    for _range in range_list:
        first_cell = ws[_range.split(':')[0]] #first cell of each range
        last_cell = ws[_range.split(':')[1]]
        rows = ws[_range] #big set of sets; each cell within each range
        fill_in(list(rows),first_cell,last_cell)   

作为参考,rows看起来像这样: ((<Cell 'Sheet1'.A1>, <Cell 'Sheet1'.B1>, <Cell 'Sheet1'.C1>, <Cell 'Sheet1'.D1>, <Cell 'Sheet1'.E1>),)

这就是新的Excel工作表的样子:前7行变得混乱和混乱。

Results of Upper Excel sheet

考虑到我上面的代码,我可以包含/做什么来跳过Excel表格的前7行或排除这些行未合并?

python excel python-3.x openpyxl
2个回答
2
投票

qazxsw poi是一个列表,所以你只需要在索引30之后开始你的迭代(6行* 5列)

merged_cell_ranges

1
投票

这对我有用。

for _range in range_list[30:]:
© www.soinside.com 2019 - 2024. All rights reserved.