Python将多份excel表格整理成一份表格

yipeiwu_com6年前Python基础

利用Python将多份excel表格整理成一份表格,抛弃过去逐份打开复制粘贴的方式。

直接附上代码:

import xlrd 
import xlwt 
import os 
from xlutils.copy import copy 
import os.path 
from xlwt import * 
dir = input("输入文件路径\n"); 
start_row = input("输入需要读取起始行号\n"); 
start_row = int(start_row) 
end_row = input("输入结束行,输入0表示有内容的最后一行\n") 
end_row = int(end_row) 
#dir = 'E:\毕业资料\2013电2\\' 
all_file = []; 
def min_s(a ,b): 
 if a == 0: 
  return b 
 if (a >b): 
  return b 
 else: 
  return a 
#遍历所有同学文件 
for parent,folder,filename in os.walk(dir): 
 for file,x in zip(filename,range(len(filename))): 
  file = os.path.join(parent,filename[x]) 
  print(filename[x]) 
  all_file.append(file) 
print("\n文件总数:",len(all_file)) 
if os.path.exists("result.xls"): 
 os.remove("result.xls") 
w = xlwt.Workbook() 
row = 0; 
ws = w.add_sheet('sheet1',cell_overwrite_ok=True) 
style = XFStyle()       
fnt = Font()              
fnt.height = 240   
fnt.name = u'宋体' 
style.font = fnt   
align = Alignment() 
align.horz = 2 
style.alignment = align 
for single_file_path in all_file: 
 data = xlrd.open_workbook(single_file_path); 
 sheet = data.sheet_by_index(0) 
 if sheet.nrows >= start_row: 
  for i in range(start_row-1,min_s(end_row,sheet.nrows)): 
   list = sheet.row_values(i) 
   for col in range(0,len(list)): 
    ws.write(row,col,list[col],style) 
   row = row + 1; 
 else: 
  print("非法填写的表格名称:"+single_file_path) 
 #写入目标文件 
 
print("运行结束,结果保存在result.xls文件里\n") 
print("对于日期,可将对应单元格设置为为日期格式便可正确显示\n" 
  "对于超长数字例如身份证号码,设置为文本格式即可\n") 
w.save('result.xls') 
os.system("pause") 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python基础篇之初识Python必看攻略

Python基础篇之初识Python必看攻略

Python简介 python的创始人为吉多·范罗苏姆(Guido van Rossum)。1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序...

python字典排序实例详解

本文实例分析了python字典排序的方法。分享给大家供大家参考。具体如下: 1、 准备知识: 在python里,字典dictionary是内置的数据类型,是个无序的存储结构,每一元素是k...

解决Python使用列表副本的问题

要使用一个列表的副本,要用切片进行列表复制,这样会形成两个独立的列表。 切记不要将列表赋值给一个列表,因为这样并不能得到两个列表。 1、使用赋值语法创建列表副本的问题 下边就将列表赋值,...

OpenCV 轮廓检测的实现方法

OpenCV 轮廓检测的实现方法

轮廓概述 轮廓可以简单认为成将连续的点(连着边界)连在一起的曲线,具有相同的颜色或者灰度。轮廓在形状分析和物体的检测和识别中很有用。  为了更加准确,要使用二值化图像...

浅谈function(函数)中的动态参数

我们可向函数传递动态参数,*args,**kwargs,首先我们来看*args,示例如下: 1.show(*args) def show(*args): print(args,typ...