本次是在原來有一定格式的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')
到了講怎么在原有的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()
釋放內存