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实现查找字符串数组最长公共前缀。分享给大家供大家参考,具体如下: 编写一个函数来查找字符串数组中的最长公共前缀。 class Solution: def...

PyQt5 加载图片和文本文件的实例

PyQt5 加载图片和文本文件的实例

首先我们来看一组效果 选择图片文本设置完以后 选择过程中 核心代码解释 # 这个函数是用来打开电脑的资源管理器选择照片用的 def loadFile(self):...

使用python+whoosh实现全文检索

whoosh的官方介绍:http://whoosh.readthedocs.io/en/latest/quickstart.html 因为做的是中文的全文检索需要导入jieba工具包以及...

python 通过手机号识别出对应的微信性别(实例代码)

python 通过手机号识别出对应的微信性别,具体代码如下所述: def getGender(self,tel): self.d(resourceId="com.tencent....

Python的加密模块md5、sha、crypt使用实例

MD5(Message-Digest Algorithm 5) 模块用于计算信息密文(信息摘要),得出一个128位的密文。sha模块跟md5相似,但生成的是160位的签名。使用方法是相同...