Python Excel 操作
如有错漏之处烦请告知,十分感谢!
本文使用
xlrd
作为读取库,xlwt
作为写入库,中间工具库xlutils
。
写入
python 对excel进行写入/修改操作可以使用xlwt
库。该库支持对于xls,xlsx格式的写入、修改、设置单元格格式。
- 安装
xlwt
库
pip install xlwt
- 新建99乘法表.xls文件
import xlwt
wb=xlwt.Workbook()
sheet=wb.add_sheet('99乘法表')=
wb.save('99乘法表.xls')
- 往99乘法表.xls文件内写入数据
import xlwt
wb = xlwt.Workbook()
sheet = wb.add_sheet('99乘法表')
# 写入数据
# 写入行列的数字
for i in range(1, 10): sheet.write(i, 0, i)
for i in range(1, 10): sheet.write(0, i, i)
# 写入行乘以列的结果
for i in range(1, 10):
for j in range(1, i + 1):
sheet.write(i, j, str(i) + '*' + str(j) + '=' + str(i * j))
wb.save('99乘法表.xls')
读取
python 对excel进行读取操作可以使用xlrd
库。该库支持对于xls,xlsx格式的读取。
- 安装
xlrd
库
pip install xlrd
- 读取内容
import xlrd
excel = xlrd.open_workbook('99乘法表.xls')
sheet = excel.sheet_by_index(0)
for i in range(1, 10):
for j in range(1, i + 1):
print(sheet.cell(i, j).value, end=',')
print()
输出结果:
1*1=1,
2*1=2,2*2=4,
3*1=3,3*2=6,3*3=9,
4*1=4,4*2=8,4*3=12,4*4=16,
5*1=5,5*2=10,5*3=15,5*4=20,5*5=25,
6*1=6,6*2=12,6*3=18,6*4=24,6*5=30,6*6=36,
7*1=7,7*2=14,7*3=21,7*4=28,7*5=35,7*6=42,7*7=49,
8*1=8,8*2=16,8*3=24,8*4=32,8*5=40,8*6=48,8*7=56,8*8=64,
9*1=9,9*2=18,9*3=27,9*4=36,9*5=45,9*6=54,9*7=63,9*8=72,9*9=81,
修改
xlutils
(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。其实际也只是在xlrd.Book和xlwt.Workbook之间建立了一个管道而已
- 安装
xlutils
库
pip install xlutils
- 修改*为×
import xlwt
import xlrd
from xlutils.copy import copy
old_excel = xlrd.open_workbook('99乘法表.xls')
old_sheet = old_excel.sheet_by_index(0)
new_excel = copy(old_excel)
new_sheet = new_excel.get_sheet(0)
for i in range(1, 10):
for j in range(1, 10):
new_sheet.write(i, j, old_sheet.cell(i, j).value.replace('*', 'x'))
new_excel.save('99乘法表_modify.xls')