Python练习-合并excel表格

前言: 这个栗子本来打算是要合并自己下载的数据集,但是尝试了好久!!才发现是.xls文件损坏了…我忍…在练习过程遇到不少bug,若是小伙伴有疑问可以提一提,说不定我遇到过,恍恍惚惚…

代码:

'''
#excel_combine.py
操作:实例化Excel_Combine_tool(),参数有2个:文件夹位置,表单名字
再save()方法
说明:代码中print()方法多为调试作用
最后文件在该源文件目录下
'
''
import xlrd
import xlwt
from numpy import *
import os
class Excel_combine_tool:
file_array = []#存放多个文件名字
file_location = ''#多个文件所在的文件夹地址
n_file = 0#文件个数
sheet_name = ''#表单名字
def __init__(self,file_location,sheet_name):
self.file_location = file_location
self.sheet_name = sheet_name
#获得所有excel表格文件列表
def get_all_excel(self):
self.file_array = [fname for fname in os.listdir(self.file_location)
if os.path.isfile(os.path.join(self.file_location,fname)) and fname.endswith('.xlsx')]
print('当前文件夹有%d个.xlsx文件'%len(self.file_array))
return self.file_array
#将所有文件读到列表
def read_in(self):
self.n_file = len(self.get_all_excel())
list = []
for i in range(0,self.n_file):
complete_fname = self.file_location + '\\' + self.file_array[i]
#print(complete_fname)
table = xlrd.open_workbook(complete_fname)
try:
sheet = table.sheet_by_name(self.sheet_name)
except:
print('没有找到Sheet1,请更换表格名字')
nrows = sheet.nrows
ncols = sheet.ncols
#忽略表格第一行title
for j in range(1,nrows):
row_list = []
for k in range(0,ncols):
row_list.append(sheet.cell(j,k).value)#读取单元格数据
list.append(row_list)
#print(list)
return list
#最终保存
def save(self):
my_list = self.read_in()
file = xlwt.Workbook()
table = file.add_sheet('Sheet1')
for i in range(len(my_list)):
for j in range(len(my_list[i])):
table.write(i,j,my_list[i][j])
print('已经合并,请检查')
file.save('new.xls')

后话: 我将在另一篇博客提供python操作文件,文件夹的知识。学习输入输出会很有用的。

———关注我的公众号,一起学数据挖掘————
这里写图片描述

猜你喜欢

转载自blog.csdn.net/crozonkdd/article/details/79304732