python 读写excel(合并单元格)

您所在的位置:网站首页 快速定位合并单元格位置 python 读写excel(合并单元格)

python 读写excel(合并单元格)

2023-10-20 00:03| 来源: 网络整理| 查看: 265

文章目录 读 Excel 合并单元格内容读取合并单元格的内容 写 Excel 写入时合并单元格

读 Excel 合并单元格内容

在这里插入图片描述 以下主要是演示读取日期类型数据

# -*- coding: utf-8 -*- import xlrd import xlwt from datetime import date,datetime def read_excel(excel_path): workbook = xlrd.open_workbook(excel_path) sheet2 = workbook.sheet_by_name('sheet2') # sheet的名称,行数,列数 nrows = sheet2.nrows # 获得所有的行数,int类型 ncols = sheet2.ncols # 获得所有的列数,int类型 # 获取单元格内容 print (sheet2.cell(1,0).value) print (sheet2.cell_value(1,0)) print (sheet2.row(1)[0].value.encode('utf-8')) # 获取单元格内容的数据类型 print("1_0_data_type:",sheet2.cell(1, 0).ctype) # 小杰 print("2_2_data_type:",sheet2.cell(2, 2).ctype) # 1991/11/12 print("2_1_data_type:",sheet2.cell(2, 1).ctype) # 22 print("2_0_data_type:",sheet2.cell(2, 0).ctype) # 小胖 print("2_4_data_type:",sheet2.cell(2, 4).ctype) # 空值(这里是合并单元格的原因) date_value = xlrd.xldate_as_tuple(sheet2.cell(2, 2).value,0) print('date_value',date_value) # (1991, 11, 12, 0, 0, 0) print(date(*date_value[:3])) # 1991-11-12 print(date(*date_value[:3]).strftime('%Y/%m/%d')) # '1991/11/12' for row in range(nrows): myRowValue2 = sheet2.cell(row,2) # 获得第i行第j列 if myRowValue2.ctype ==3: date_value = xlrd.xldate_as_tuple(sheet2.cell_value(row, 2), workbook.datemode) date_tmp = date(*date_value[:3]).strftime('%Y/%m/%d') print('date_tmp',date_tmp) if __name__ == '__main__': excel_path = './a.xls' read_excel(excel_path)

ctype : 0=empty,1=string, 2=number, 3=date, 4=boolean, 5=error

读取合并单元格的内容

读取合并单元格的内容,添加:formatting_info=True

workbook = xlrd.open_workbook(excel_path,formatting_info=True) print("sheet2.merged_cells",sheet2.merged_cells) print(sheet2.cell_value(1, 4)) # (1,3,4,5) print(sheet2.cell_value(3, 4)) # (3,6,4,5) print(sheet2.cell_value(7, 2)) # (7,8,2,5) ''' 好朋友 同学 暂无 '''

merged_cells返回的这四个参数的含义是:(row,row_range,col,col_range),其中[row,row_range)包括row,不包括row_range,col也是一样。 即(1, 3, 4, 5)的含义是:第1到2行(不包括3)合并,(7, 8, 2, 5)的含义是:第2到4列合并。

利用这个,可以分别获取合并的三个单元格的内容:

写 Excel 写入时合并单元格 import xlwt def set_style(name,height,bold=False): ''' 设置单元格样式 ''' style = xlwt.XFStyle() # 初始化样式 font = xlwt.Font() # 为样式创建字体 font.name = name # 'Times New Roman' font.bold = bold font.color_index = 4 font.height = height # borders= xlwt.Borders() # borders.left= 6 # borders.right= 6 # borders.top= 6 # borders.bottom= 6 style.font = font # style.borders = borders return style #写excel def write_excel(): Workbook = xlwt.Workbook() #创建工作簿 sheet1 = Workbook.add_sheet(u'sheet1',cell_overwrite_ok=True) #创建sheet row0 = [u'业务',u'状态',u'北京',u'上海',u'广州',u'深圳',u'状态小计',u'合计'] column0 = [u'机票',u'船票',u'火车票',u'汽车票',u'其它'] status = [u'预订',u'出票',u'退票',u'业务小计'] #生成第一行 for i in range(0,len(row0)): sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True)) #生成第一列和最后一列(合并4行) i, j = 1, 0 while i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3