赞
踩
- # -*- coding: utf-8 -*-
- import xlrd
-
- def read_excel():
- # 打开文件
- workbook = xlrd.open_workbook(r'D:\demo1.xlsx')
- # 获取所有sheet
- print(workbook.sheet_names()) # 列表形式返回
- # sheet1_name = workbook.sheet_names()[0]
-
- # 根据sheet索引或者名称获取sheet内容
- # sheet1 = workbook.sheet_by_index(0) # sheet索引从0开始
- sheet1 = workbook.sheet_by_name('sheet1')
-
- # sheet的名称,行数,列数
- print(sheet1.name,sheet1.nrows,sheet1.ncols)
-
- # 获取整行和整列的值(数组)
- rows = sheet1.row_values(3) # 获取第四行内容
- cols = sheet1.col_values(2) # 获取第三列内容
- print(rows)
- print(cols)
-
- # 三种获取单元格内容的方式
- print(sheet1.cell(1,0).value)
- print(sheet1.cell_value(1,0))
- print(sheet1.row(1)[0].value)
-
- # 获取单元格内容的数据类型
- print(sheet1.cell(1,0).ctype)
-
-
- if __name__ == '__main__':
- read_excel()
1、Python读取excel中单元格内容为日期的方式
python读取excel中单元格的内容返回的有5种类型,即上面例子中的ctype:
ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
即date的ctype=3,这时需要使用xlrd的xldate_as_tuple来处理为date格式,先判断表格的ctype=3时xldate才能开始操作。现在命令行看下:
- >>> sheet2.cell(2,2).ctype #1990/2/22
- 3
- >>> sheet2.cell(2,1).ctype #24
- 2
- >>> sheet2.cell(2,0).ctype #小胖
- 1
- >>> sheet2.cell(2,4).ctype #空值(这里是合并单元格的原因)
- 0
- >>> sheet2.cell(2,2).value #1990/2/22
- 33656.0
- >>> xlrd.xldate_as_tuple(sheet2.cell_value(2,2),workbook.datemode)
- (1992, 2, 22, 0, 0, 0)
- >>> date_value = xlrd.xldate_as_tuple(sheet2.cell_value(2,2),workbook.datemode)
- >>> date_value
- (1992, 2, 22, 0, 0, 0)
- >>> date(*date_value[:3])
- datetime.date(1992, 2, 22)
- >>> date(*date_value[:3]).strftime('%Y/%m/%d')
- '1992/02/22'
即可以做下简单处理,判断ctype是否等于3,如果等于3,则用时间格式处理:
- if (sheet.cell(row,col).ctype == 3):
- date_value = xlrd.xldate_as_tuple(sheet.cell_value(rows,3),book.datemode)
- date_tmp = date(*date_value[:3]).strftime('%Y/%m/%d')
2、获取合并的单元格
读取文件的时候需要将formatting_info参数设置为True,默认是False,所以上面获取合并的单元格数组为空,
- >>> workbook = xlrd.open_workbook(r'F:\demo.xlsx',formatting_info=True)
- >>> sheet2 = workbook.sheet_by_name('sheet2')
- >>> sheet2.merged_cells
- [(7, 8, 2, 5), (1, 3, 4, 5), (3, 6, 4, 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列合并。
- '''
利用这个,可以分别获取合并的三个单元格的内容:
- >>> 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)
- 暂无
发现规律了没?是的,获取merge_cells返回的row和col低位的索引即可! 于是可以这样一劳永逸:
- >>> merge = []
- >>> for (rlow,rhigh,clow,chigh) in sheet2.merged_cells:
- merge.append([rlow,clow])
-
- >>> merge
- [[7, 2], [1, 4], [3, 4]]
- >>> for index in merge:
- print sheet2.cell_value(index[0],index[1])
-
- 暂无
- 好朋友
- 同学
- # -*- coding: utf-8 -*-
- 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= 10
- # borders.right= 10
- # borders.top= 10
- # borders.bottom= 10
-
- style.font = font
- # style.borders = borders
-
- return style
-
-
- #写excel
- def write_excel():
- f = xlwt.Workbook() #创建工作簿
- '''
- 创建第一个sheet:
- sheet1
- '''
- sheet1 = f.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行)
- '''
- write_merge(x,x+3,y,y+3): x表示行,y表示列; x+3表示夸行数,y+3表示夸列数。
- 前两个数一样表示不跨行;后两个一样表示不跨列。
- '''
- i, j = 1, 0
- while i < 4*len(column0) and j < len(column0):
- sheet1.write_merge(i,i+3,0,0,column0[j],set_style('Arial',220,True)) #第一列
- sheet1.write_merge(i,i+3,7,7) #最后一列"合计"
- i += 4 # 控制每个合并框列跨度
- j += 1
- sheet1.write_merge(21,21,0,1,u'合计',set_style('Times New Roman',220,True))
-
- #生成第二列
- i = 0
- while i < 4*len(column0):
- for j in range(0,len(status)):
- sheet1.write(j+i+1,1,status[j])
- i += 4
-
- f.save('demo1.xlsx') #保存文件
-
- if __name__ == '__main__':
- write_excel()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。