用openpyxl读取新版Excel文件xlsx,并判断是否为合并单元格
专栏:ExASIC Nov. 10, 2024, 2:07 p.m. 47 阅读
用openpyxl读取新版Excel文件xlsx,并判断是否为合并单元格

打开Excel工作簿

先导入openpyxl库,如果提示没有安装就用命令pip install openpyxl安装一下。

再用load_workbook('filename.xlsx')读入Excel xlsx文件。代码如下:

import openpyxl
book = openpyxl.load_workbook('test.xlsx')

打开Excel工作表

方法一:跟据工作表名称打开:

sheet0 = book['Sheet1']

方法二:根据工作表序号打开:

book.sheetnames是工作表名称的列表,比如:['Sheet1', 'Sheet2', 'Sheet3']

sheet0_name = book.sheetnames[0]
sheet0 = book[sheet0_name]

for遍历所有单元格

假设有如下的Excel表:

____________________________________________________________________________________________________
|           |     A    |     B    |     C    |     D    |     E    |     F    |     G    |     H    | 
____________________________________________________________________________________________________
|     1     |          |          |          |          |          |          |     G1   |     H1   | 
____________________________________________________________________________________________________
|     2     |          |          |          |     D2   |     E2~H2                                 | 
____________________________________________________________________________________________________
|     3     |                               A3~H3                                                   | 
____________________________________________________________________________________________________

sheet0.iter_rows()遍历所有行,然后再遍历所有列。遍历后得到的并不是单元格的数据,而是cell类型的对象(<Cell 'Sheet1'.A1>)。单元格的数据在cell.value里。

for row in sheet0.iter_rows():
    print('-' * 30)
    for cell in row:
        print(cell, cell.value, ',', end=' ')

执行结果如下:

<Cell 'Sheet1'.A1> None , <Cell 'Sheet1'.B1> None , <Cell 'Sheet1'.C1> None , <Cell 'Sheet1'.D1> None , <Cell 'Sheet1'.E1> None , <Cell 'Sheet1'.F1> None , <Cell 'Sheet1'.G1> G1 , <Cell 'Sheet1'.H1> H1 , 
 ------------------------------
<Cell 'Sheet1'.A2> None , <Cell 'Sheet1'.B2> None , <Cell 'Sheet1'.C2> None , <Cell 'Sheet1'.D2> D2 , <Cell 'Sheet1'.E2> E2~H2 , <MergedCell 'Sheet1'.F2> None , <MergedCell 'Sheet1'.G2> None , <MergedCell 'Sheet1'.H2> None , 
 ------------------------------
<Cell 'Sheet1'.A3> A3~H3 , <MergedCell 'Sheet1'.B3> None , <MergedCell 'Sheet1'.C3> None , <MergedCell 'Sheet1'.D3> None , <MergedCell 'Sheet1'.E3> None , <MergedCell 'Sheet1'.F3> None , <MergedCell 'Sheet1'.G3> None , <MergedCell 'Sheet1'.H3> None , 
 ------------------------------

判断是否是合并单元格

从遍历的结果来看,cell有两种:

  • <Cell 'Sheet1'.A1>

  • <MergedCell 'Sheet1'.G2>

所以,我们可以用type(cell)得到class的类型,并判断,就可以知道是否有合并单元格。

for row in sheet0.iter_rows():
    for cell in row:
        if type(cell) == openpyxl.cell.cell.MergedCell:
           print('merged', end=' ')
        else:
            print(cell.value, end=' ')

    print('')

执行结果如下:

None None None None None None G1 H1 
None None None D2 E2~H2 merged merged merged 
A1~H3 merged merged merged merged merged merged merged 
感谢阅读,更多文章点击这里:【专栏:ExASIC】
最新20篇 开设专栏