37,721
社区成员
发帖
与我相关
我的任务
分享
# -*- coding: utf-8 -*-
import xlrd,xlwt
from os import listdir
from os.path import isfile, join, splitext
from xlutils.filter import process, XLRDReader, XLWTWriter
input_file = 'E:\\demo\\read_test01.xls'
output_file = 'E:\\demo\\write_test.xls'
path = 'E:\\demo'
oldrows = 0
def copy2(r_file):
global oldrows
'''
附带样式的copy
xlrd打开文件,必须加参数formatting_info=True
'''
w = XLWTWriter()
process(
XLRDReader(r_file,'unknown.xls'),
w
)
w_file, style_list = w.output[0][1], w.style_list
w_sheet = w_file.get_sheet(0)
r_sheet = r_file.sheet_by_index(0)
rows = r_sheet.nrows #获取行数
cols = r_sheet.ncols #获取列数
for row in range(rows):
for col in range(cols):
xf_index = r_sheet.cell_xf_index(row, col)
value=r_sheet.cell(row,col).value
w_sheet.write(row, col, value, style_list[xf_index])
oldrows += rows + 1
return w_file
def get_files(path,file_list):
for file in listdir(path):
file_path = join(path, file)
if isfile(file_path) == True and splitext(file_path)[1] == '.xls':
file_list.append(file_path)
if __name__ == "__main__":
file_list = []
# wb = xlwt.Workbook()
# ws = wb.add_sheet('My Worksheet')
get_files(path,file_list)
for input_file in file_list:
rb = xlrd.open_workbook(input_file, formatting_info=True)
wb = copy2(rb)
wb.save(output_file)