python如何读取多个excel合并到一个excel中

V0_fly 2018-01-09 05:06:00
网上找了很多资料了,我已经使用xlwt+xlrd+xlutils实现了内容+格式的完全拷贝,但仅仅只能处理一个excel,想要多个合并为一个就不行(以追加写的形式),格式就会乱,这里先贴上目前的代码吧。有没有人帮帮我解决下这个问题。代码如下:
# -*- 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)
...全文
2002 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
galaxybamboo1 2019-04-02
  • 打赏
  • 举报
回复
这么多数据写excel?怎么分析,有什么用? 肯定入到数据库里做个查询接口啊
ww2019xy 2019-01-10
  • 打赏
  • 举报
回复
厉害 我也试试 这种方式
硅谷少年 2019-01-10
  • 打赏
  • 举报
回复
是的,我每月将近一万个excel文件,每个文件1-4M,就是受不了VBA太慢(即使ADO SQL也平均3秒处理一个文件)才找其它方法的。
JOSON. 2018-07-17
  • 打赏
  • 举报
回复
直接用VBA吧,简单方便
阿凯99 2018-07-16
  • 打赏
  • 举报
回复
引用 3 楼 V0_fly 的回复:
看这几天都没人回复,我已经解决问题了,就不用麻烦各位了,顺便一提,最后我是用python调用vba程序实现的



python调用vba程序,运行速度超慢!
qq_42609544 2018-07-08
  • 打赏
  • 举报
回复
求代码,同样问题找了好久,还是不会
陈年椰子 2018-01-11
  • 打赏
  • 举报
回复
V0_fly 2018-01-11
  • 打赏
  • 举报
回复
看这几天都没人回复,我已经解决问题了,就不用麻烦各位了,顺便一提,最后我是用python调用vba程序实现的
V0_fly 2018-01-09
  • 打赏
  • 举报
回复
引用 1 楼 TheLittlePython 的回复:
直接用pandas 的concat 满足不了要求吗
嗯嗯。不行。
TheLittlePython 2018-01-09
  • 打赏
  • 举报
回复
直接用pandas 的concat 满足不了要求吗

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧