

xlwt xlsxwriter会替换之前的 不能追加

第一种比较简单
第二种难
主要是巩固基础 所以就按第二种的写
安装xlsxwriter

然后是报了个警告
说是pip有点老要更新
这样就更新完毕

在安装 xlrd

创建三个excel

每一个excel 有两个sheet 东西都不一样

第一个是课 第二个是书

老版office2007不支持这样多shell存 所以网上直接在线编辑文档后下载
写不出来都行 看懂代码就行
老师代码没看懂 比较绕 自己写了个
import xlrd,xlsxwriter
#设置要合并的所有文件
road="D:/py/Excel合并用的Excel/"
allxlsPath=[road+"test1.xls",road+"test2.xls",road+"test3.xls"]
#合并后生成的文件
endxlsPath=road+"combineExcel.xls"
#变量
#储存一个标签的结果
sValue=[]
#储存第一个文件的sheet信息
#根据第一个为基准创建新的表格
shname=[]
#下面是各种方法
#读取第一个待读文件 获取sheet数
xls=xlrd.open_workbook(allxlsPath[0])
#获取所有sheet
sh=xls.sheets()
for sheet in sh:
shname.append(sheet.name)
sValue.append([])
#获取某个文件内容 返回当前sheet内容
def getfile(path,shNum):
#打开文件 覆盖之前的
xls=xlrd.open_workbook(path)
#根据sheet名打开一页
table=xls.sheet_by_name(shname[shNum])
return table
#获取返回第一行的值
def getHeadValue(table):
return table.row_values(0)
#获取返回除了第一行所有行的值
def getOtherValue(table):
#获取某个sheet的行数
num=table.nrows
rValue=[]
for row in range(1,num):
#返回一整行
rdata=table.row_values(row)
rValue.append(rdata)
return rValue
#依次读取各sheet的内容
#依次读取各文档当前sheet的内容
for shNum in range(0,len(shname)):
fileValue=sValue[shNum]
table=getfile(allxlsPath[0],shNum)
#加入标题
fileValue.append(getHeadValue(table))
for path in allxlsPath:
print("正在读取文件"+str(path)+"的第"+str(shNum)+"个shell的...")
table=getfile(path,shNum)
#加入每一个文档的除了第一行的每一行
for value in getOtherValue(table):
fileValue.append(value)
#print(sValue[0])
#print(sValue[1])
#由于append具有叠加关系 分析可得所有信息在sValue中储存
#打开最终写入的文件 大写别忘了 我是在这卡主了
wbl=xlsxwriter.Workbook(endxlsPath)
#遍历每个sheet的数据
for s in range(0,len(shname)):
#取汇总过的一个sheet的数据
sheetData=sValue[s]
#创建一个新的sheet
thisSheet=wbl.add_worksheet(shname[s])
#将多个标签写入新文件中
for a in range(0,len(sheetData)):
for b in range(0,len(sheetData[a])):
data=sheetData[a][b]
#创建一个sheet工作对象
thisSheet.write(a,b,data)
#写入需要关闭才会保存生成
wbl.close()
思路是把每个重复的第一行 提取出来

之后只读第一行之后的
以第一个文档为基准
然后把他们加到一个数组里
sValue打印出来
用在线json转换 是这个格式
http://www.bejson.com/index.php

很多东西老师也没讲 自己去查
最终


sheet将以第一个文档为基准

怎么说作为练习难度跳跃幅度比较大 可能会直接劝退
和C#有点不同的是 方法必须写在用它代码的上方
就是方法也要初始化 是类似于一条线走下来的
网友评论