本文最后更新于:2024年1月14日 晚上

Python输出的数据用Excel文件查看往往更直观,而且Excel中的数据也常常需要读取到Python程序中。Python的xlrd和xlwt模块便是为此而生。文本记录这两个模块的使用方法。

测试用例

使用read_test.xlsx作为读取excel的测试文件。其中两个工作表,分别为:

模块安装

用pip可以方便地安装

1
2
pip install xlrd
pip install xlwt

xlrd

读取excel文件(xls,xlsx)

1
2
3
4
5
6
7
8
import xlrd


## 读取excel文件
try:
data = xlrd.open_workbook('read_test.xlsx')
except Exception as err:
print(err)

获取工作表信息

1
2
3
4
5
6
7
## 获取工作表信息
print(len(data.sheets()))
sheet_names = data.sheet_names()
print(sheet_names)

>>>2
['信息表2', '信息表1']

获取工作表内容

通过索引

1
2
3
4
5
6
7
8
9
## 通过索引获取工作表内容
info_sheet_1 = data.sheet_by_index(0)
info_sheet_2 = data.sheet_by_index(1)

print(f'sheet :{info_sheet_1.name} row_num: {info_sheet_1.nrows} column_num: {info_sheet_1.ncols}')
print(f'sheet :{info_sheet_2.name} row_num: {info_sheet_2.nrows} column_num: {info_sheet_2.ncols}')

>>> sheet :信息表1 row_num: 5 column_num: 7
sheet :信息表2 row_num: 5 column_num: 7

通过名称

1
2
3
4
5
6
7
8
9
10
## 通过名称获取工作表内容
sheet_names = data.sheet_names()
info_sheet_1 = data.sheet_by_name(sheet_names[0])
info_sheet_2 = data.sheet_by_name(sheet_names[1])

print(f'sheet :{info_sheet_1.name} row_num: {info_sheet_1.nrows} column_num: {info_sheet_1.ncols}')
print(f'sheet :{info_sheet_2.name} row_num: {info_sheet_2.nrows} column_num: {info_sheet_2.ncols}')

>>> sheet :信息表1 row_num: 5 column_num: 7
sheet :信息表2 row_num: 5 column_num: 7

获取工作表中数据内容

获取工作表行信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
## 获取工作表行信息
for i in range(info_sheet_1.nrows):
print(info_sheet_1.row_values(i))
for i in range(info_sheet_2.nrows):
print(info_sheet_2.row_values(i))

>>> ['信息表 1', '', '', '', '', '', '']
['姓名', '性别', '年龄', '籍贯', '手机', '邮箱', '备注']
['淑芬', '女', 32.0, '山东', 12345678900.0, 'Shufen@163.com', '爱好读书']
['建国', '男', 43.0, '北京', 13265498700.0, 'Jianguo@126.com', '儿女双全']
['大胖', '男', 18.0, '甘肃', 12435698700.0, 'Dapang@110.com', '']
['信息表 2', '', '', '', '', '', '']
['姓名', '性别', '年龄', '籍贯', '手机', '邮箱', '备注']
['三凤', '女', 28.0, '河南', 12388678900.0, 'sanfeng@163.com', '']
['王聪', '男', 31.0, '浙江', 13266498700.0, 'Wangcong@119.com', '']
['Lilei', '男', 22.0, 'Australia', 12499998700.0, 'Lilei@130.com', '英语流利']

获取工作表列信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
## 获取工作表列信息
for i in range(info_sheet_1.ncols):
print(info_sheet_1.col_values(i))
for i in range(info_sheet_2.ncols):
print(info_sheet_2.col_values(i))

>>>['信息表 1', '姓名', '淑芬', '建国', '大胖']
['', '性别', '女', '男', '男']
['', '年龄', 32.0, 43.0, 18.0]
['', '籍贯', '山东', '北京', '甘肃']
['', '手机', 12345678900.0, 13265498700.0, 12435698700.0]
['', '邮箱', 'Shufen@163.com', 'Jianguo@126.com', 'Dapang@110.com']
['', '备注', '爱好读书', '儿女双全', '']
['信息表 2', '姓名', '三凤', '王聪', 'Lilei']
['', '性别', '女', '男', '男']
['', '年龄', 28.0, 31.0, 22.0]
['', '籍贯', '河南', '浙江', 'Australia']
['', '手机', 12388678900.0, 13266498700.0, 12499998700.0]
['', '邮箱', 'sanfeng@163.com', 'Wangcong@119.com', 'Lilei@130.com']
['', '备注', '', '', '英语流利']

获取工作表指定位置信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
## 获取工作表指定位置信息
print(info_sheet_1.cell(2,1).value)
print(info_sheet_1.cell_value(2,1))
print(info_sheet_1.row(2)[1].value)
print(info_sheet_1.row_values(2)[1])
print(info_sheet_1.col(1)[2].value)
print(info_sheet_1.col_values(1)[2])

>>>女





获取工作表中数据的类型

1
2
3
4
5
6
7
8
9
10
11
## 获取工作表中数据的类型
for i in range(info_sheet_1.ncols):
print(info_sheet_1.cell(2,i).ctype)

>>> 1
1
2
1
2
1
1

# 说明:ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

获取合并单元格信息

1
2
3
4
## 获取合并单元格信息
print(info_sheet_1.merged_cells)

>>> [(0, 1, 0, 7)]

这返回的四个数字定位了一组合并单元格操作,如果把四个数表示为(A,B,C,D),可以这样理解:

  • 合并单元格的起始(左上角)单元格(在合并区域内)坐标为[A,C]
  • 合并单元格的结束(右下角)单元格(在合并区域外)坐标为[B,D]

xlwt

建立xlwt对象

1
2
3
4
import xlwt

## 建立xlwt对象
wb = xlwt.Workbook()

建立工作表

1
2
3
4
5
6
7
8
9
## 建立工作表
test_sheet_1 = xlsx_writer.add_sheet('Test Sheet 1')
test_sheet_2 = xlsx_writer.add_sheet('Test Sheet 2')

try:
xlsx_writer.save('write_test.xlsx') # 保存xlsx
xlsx_writer.save('write_test.xls') # 保存xls
except Exception as err:
print(err)

向数据表写入内容

1
2
3
4
5
6
7
8
9
10
11
12
13
## 向数据表写入内容
test_sheet_1.write(1,1,123)
test_sheet_1.write(1,2,110)
test_sheet_1.write(1,3,xlwt.Formula("B2+C2"))
test_sheet_1.write(1,4,'test')
test_sheet_1.write(1,5,True)
test_sheet_2.write(3,3,xlwt.Formula("'{}'!$B$2+'{}'!$D$2".format(test_sheet_1.name,test_sheet_1.name)))

try:
xlsx_writer.save('write_test.xlsx') # 保存xlsx
xlsx_writer.save('write_test.xls') # 保存xls
except Exception as err:
print(err)

设置列宽、行高

1
2
3
4
5
6
7
8
## 设置列宽、行高
test_sheet_1.col(0).width = 400*30
test_sheet_1.row(0).height = 1000
try:
xlsx_writer.save('write_test.xlsx') # 保存xlsx
xlsx_writer.save('write_test.xls') # 保存xls
except Exception as err:
print(err)

设置内容样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
## 初始化样式
style = xlwt.XFStyle() # 样式类实例

## 创建字体
font = xlwt.Font() # 字体类实例
font.name = 'Times New Roman' # 字体名称
font.bold = True # 加粗
font.italic =True # 倾斜
font.height = 300 # 字号 200 为 10 points
font.colour_index=3 # 颜色编码

## 创建边框
borders= xlwt.Borders() # 边框类实例
borders.left= 6
borders.right= 6
borders.top= 6
borders.bottom= 6

## 创建对齐
alignment = xlwt.Alignment() # 对齐类实例
#alignment.horz = xlwt.Alignment.HORZ_LEFT # 水平左对齐
#alignment.horz = xlwt.Alignment.HORZ_RIGHT # 水平右对齐
alignment.horz = xlwt.Alignment.HORZ_CENTER # 水平居中
#alignment.vert = xlwt.Alignment.VERT_TOP # 垂直靠上
#alignment.vert = xlwt.Alignment.VERT_BOTTOM # 垂直靠下
alignment.vert = xlwt.Alignment.VERT_CENTER # 垂直居中
alignment.wrap = 1 # 自动换行

## 创建模式
pattern = xlwt.Pattern() # 模式类实例
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # 固定的样式
pattern.pattern_fore_colour = xlwt.Style.colour_map['yellow'] # 背景颜色

## 应用样式
style.font = font
style.borders = borders
style.num_format_str = '#,##0.0000' # 内容格式
style.alignment = alignment
style.pattern=pattern

## 合并单元格(A,B,C,D) 表示合并左上角[A,C]和右下角[B,D]单元格坐标(均在合并单元格内部)
test_sheet_1.write_merge(3, 5, 3, 5, ' Merge ',style) # ' Merge ' 为写入内容,应用 style 样式

test_sheet_1.write(0, 0, 1234567.890123,style) # 向[0,0]坐标单元格写入数据,应用style样式

style.num_format_str = '#,##0.000%' # 内容格式
test_sheet_1.write(6, 0, 67.8123456,style) # 整数部分用逗号分隔,小数部分保留3位小数并以百分数表示

style.num_format_str = '###%' # 内容格式
test_sheet_1.write(6, 5, 0.128,style)

style.num_format_str = '###.##%' # 内容格式
test_sheet_1.write(6, 4, 0.128,style)

style.num_format_str = '000.00%' # 内容格式
test_sheet_1.write(6, 3, 0.128,style)

try:
xlsx_writer.save('write_test.xlsx') # 保存xlsx
xlsx_writer.save('write_test.xls') # 保存xls
except Exception as err:
print(err)

获取源码

文中测试环境与所有源码可在Github下载。



文章链接:
https://www.zywvvd.com/notes/coding/python/python-xlrd-xlwt/python-xlrd-xlwt/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Python - xlrd,xlwt模块操作excel文件
https://www.zywvvd.com/notes/coding/python/python-xlrd-xlwt/python-xlrd-xlwt/
作者
Yiwei Zhang
发布于
2020年2月25日
许可协议