python结合xlrd和xlwt操作已有excel文件(不改变格式)
使用中间库xlutils
Pip install xlutils
直接源码
import xlrd
from xlutils
.filter import process
, XLRDReader
, XLWTWriter
import glob
def Change_yaer(file_list
):
log
= open('error_log.txt','w')
for file in file_list
:
print(file)
file_name
= file.split
('.')[0].split
('\\')[-1]
try:
rb
= xlrd
.open_workbook
(file,formatting_info
=True)
w
= XLWTWriter
()
process
(XLRDReader
(rb
, 'unknown.xls'), w
)
wb
= w
.output
[0][1]
style_list
= w
.style_list
for n
, sheet
in enumerate(rb
.sheets
()):
sheet2
= wb
.get_sheet
(n
)
for r
in range(sheet
.nrows
):
for c
, cell
in enumerate(sheet
.row_values
(r
)):
if n
==0 and r
== 3 and c
== 6:
values
= '2020'
else:
values
= sheet
.cell_value
(r
,c
)
style
= style_list
[sheet
.cell_xf_index
(r
, c
)]
sheet2
.write
(r
, c
, values
, style
)
wb
.save
(f
'{file_name}.xls')
except Exception
as e
:
log
.write
(file_name
+e
+'\n')
log
.close
()
转载请注明原文地址:https://tech.qufami.com/read-25743.html