本次是在原来有一定格式的Excel文档中补充成绩。
- 安装的模块:xlwt 、 xlrd 、xlutils
xlrd的模块是只用读取xls文件,不能写文件,同理xlwt,只(新建写)不读已有的xls,
xlrd的用法:
- 打开文件:
data =xlrd.open_workbook(fime_path+'011.xls')
- 读取sheet:
table = data.sheet_by_index(0)
- 获取行数和列数:
nrows = table.nrows
ncols = table.ncols
- 读取单元格:
table.cell(i,j).value
xlwt的用法
- 初始化workbook对象:
wbk = xlwt.Workbook()
- 表单创建:
sheet = wbk.add_sheet('sheet 1')
- 写单元:
sheet.write(0,1,'test text')
- 保存:
wbk.save('test.xls')
- 详情:【https://my.oschina.net/dddttttt/blog/466103】
到了讲怎么在原有的xls文档追加。这就使用到xlutils,xlutils(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。其实际也只是在xlrd.Book和xlwt.Workbook之间建立了一个管道而已,如下图:
- 导包:
from xlutils.copy import copy
- 先用xlrd打开文件:
old_xls = xlrd.open_workbook(file_path2,formatting_info=True)
- 然后复制,使其转化成xlwt对象:
table_xlwt_b = copy(old_xls)
- 获取已有表单:
table_xlwt = table_xlwt_b.get_sheet(0)
- 修改单元格值:
table_xlwt.write(id_p,j,list[k]) #iid_p是行,j是列,list[k]是填充的值
- 保存:
table_xlwt_b.save(fime_path+"033.xls")
最后需要注意,打开原有xls文件,需要保留文档单元格的格式,需要在xlrd打开文件参数添加formatting_info=True,(默认是FALSE),同时,这参数只支持旧版的xls后缀的文件,不支持新版的xlsx后缀的文档,,如果打开xlsx会抛出异常,因此需要另存为xls文档
最后附上代码
#!coding:utf-8
import xlrd
import xlwt
import copy
from xlutils.copy import copy
fime_path="F:\\program_new\\PyCharm Community Edition 2018.2.3\\code_example\\xlwt_xlrd\\code\\"
old_xls = xlrd.open_workbook(fime_path+"022.xls", formatting_info=True)
def read_book():
data =xlrd.open_workbook(fime_path+'011.xls')
#导入表
table = data.sheet_by_index(0)
nrows = table.nrows
ncols = table.ncols
i=0
j=0
list_score = []
score = []
for i in range(1,nrows):
for j in range(6,ncols):
# print("%d%d"%(i,j))
score.append(table.cell(i,j).value)
list_score.append(score)
score=[]
return list_score
def id_position(student_id):
tabel_xlwt_ot = old_xls.sheet_by_index(0)
nrows = tabel_xlwt_ot.nrows
ncols = tabel_xlwt_ot.ncols
for i in range(3,nrows):
now_student_id = int(tabel_xlwt_ot.cell(i,0).value)
now_student_id=str(now_student_id)
if now_student_id==student_id:
return i
def write_book():
table_xlwt_b = copy(old_xls)
table_xlwt = table_xlwt_b.get_sheet(0)
list2=read_book()
print(len(list2),len(list2[1]))
for list in list2:
s_id=list[0]
print(list)
id_p = id_position(s_id)
if id_p is not None:
for (j,k) in zip(range(2,27,3),range(2,11)):
print(k,j)
table_xlwt.write(id_p,j,list[k])
else:
print(u"找不到该学号%s"%s_id)
table_xlwt_b.save(fime_path+"033.xls")
if __name__=="__main__":
write_book()
不用关闭文件,官方没有提供具体的方法关闭打开的xls文件。可以使用
book.release_resources()
释放内存