前言:

1、导入xlrd模块

2、读取excel路径(需要导入os)——创建workbook对象——sheet对象——获取excel_value值

import os
import xlrd

excel_path =os.path.join(os.path.dirname(__file__),'data/test_data.xlsx')
print(excel_path)

wb =xlrd.open_workbook(excel_path)
sheet =wb.sheet_by_name('Sheet1')
cell_value =sheet.cell_value(1,0)  # 合并的单元格,值在单元格的0,0  1,0 2,0 3,0……值为空
print(cell_value)

升级:如何将合并单元格中的所有值,取单元格左上角首个单元格的值?

解题思路:先获取合并单元格的所在行和所在列——然后遍历所有单元格的值,使用判断语句来取值

merged =sheet.merged_cells    #返回一个列表   起始行、结束行、起始列、结束列 [(1, 5, 0, 1)]
print(sheet.merged_cells)
def get_merged_cell_value(row_index,col_index):
    cell_value =None
    for (srow,erow,scol,ecol) in merged:   #遍历表格中所有合并单元格的位置信息
        if (srow<=row_index  and erow>row_index):      # 1<=2<5
            if (scol <=col_index  and ecol >col_index):       # 0<=0<1
                #如果满足条件,则把合并单元格首个单元格的值赋值给其他合并单元格
                cell_value =sheet.cell_value(srow,scol)
    return cell_value
print(get_merged_cell_value(3,0))  #取合并单元格的第3行第0列数据

若有以下表格数据,输出结果:[(1, 5, 0, 1)]  爬虫教程

 

posted on 2020-07-04 09:37  喵小超  阅读(939)  评论(0编辑  收藏  举报