Python xlrd模块 Python基于xlrd模块处理合并单元格

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python xlrd模块 Python基于xlrd模块处理合并单元格

安琪儿一直在   2021-01-29 我要评论

目的:

python能使用xlrd模块实现对Excel数据的读取,且按照想要的输出形式。

总体思路:

(1)要想实现对Excel数据的读取,需要用到第三方应用,直接应用。

(2)实际操作时候和我们实际平时打开一个文件进行操作一样,先找到文件-->打开文件-->定义要读取的sheet-->读取出内容。

Excel处理合并单元格:

已存在合并单元格如下:

xlrd中的 merged_cells 属性介绍:[code]import xlrd

import xlrd
workbook = xlrd.open_workbook('./data/test_data.xlsx')
sheet = workbook.sheet_by_name('Sheet1')
merged = sheet.merged_cells # 返回一个列表 起始行,结束行,起始列,结束列)
print(merged)

读取合并单元格中的某一个单元格的值编写成一个方法:

def get_merged_cell_value(row_index,col_index):
  cell_value = None
  for (rlow, rhigh, clow, chigh) in merged:
    if (row_index >= rlow and row_index < rhigh):
      if (col_index >= clow and col_index < chigh):
        cell_value = sheet.cell_value(rlow, clow)
  return cell_value

print( get_merged_cell_value(0,1) )

给出坐标,判断是否为合并单元格:

#方法参数为单元格的坐标(x,y),如果给的坐标是合并的单元格,输出此单元格是合并的,否则,输出普通单元格
def get_merged_cell_value(row_index,col_index):
  for (rlow, rhigh, clow, chigh) in merged:
    if (row_index >= rlow and row_index < rhigh and col_index >= clow and col_index < chigh):
      print("此单元格是合并单元格")
    else:
      print("此单元格为普通单元格")

print( get_merged_cell_value(4,3) )

##读取第3列的所有数据,并进行降序排序
clox=3
list1=[]
for i in range(1,sheet.nrows):
  cell_value=float(sheet.cell_value(i,clox))
  list1.append(cell_value)
print(list1)
list1.sort()
list1.reverse()
print(list1)

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们