您好我想使用python连接三个excels文件xlsx。
我尝试过使用openpyxl,但我不知道哪个函数可以帮助我将三个工作表附加到一个。
你有什么想法怎么做?
非常感谢
答案 0 :(得分:15)
这是一种基于pandas的方法。 (它在幕后使用openpyxl
。)
import pandas as pd
# filenames
excel_names = ["xlsx1.xlsx", "xlsx2.xlsx", "xlsx3.xlsx"]
# read them in
excels = [pd.ExcelFile(name) for name in excel_names]
# turn them into dataframes
frames = [x.parse(x.sheet_names[0], header=None,index_col=None) for x in excels]
# delete the first row for all frames except the first
# i.e. remove the header row -- assumes it's the first
frames[1:] = [df[1:] for df in frames[1:]]
# concatenate them..
combined = pd.concat(frames)
# write it out
combined.to_excel("c.xlsx", header=False, index=False)
答案 1 :(得分:5)
我使用xlrd和xlwt。假设您确实需要附加这些文件(而不是对它们进行任何实际工作),我会执行以下操作:打开要使用xlwt
写入的文件,然后为其他三个文件中的每个文件写入,遍历数据并将每一行添加到输出文件中。为了帮助您入门:
import xlwt
import xlrd
wkbk = xlwt.Workbook()
outsheet = wkbk.add_sheet('Sheet1')
xlsfiles = [r'C:\foo.xlsx', r'C:\bar.xlsx', r'C:\baz.xlsx']
outrow_idx = 0
for f in xlsfiles:
# This is all untested; essentially just pseudocode for concept!
insheet = xlrd.open_workbook(f).sheets()[0]
for row_idx in xrange(insheet.nrows):
for col_idx in xrange(insheet.ncols):
outsheet.write(outrow_idx, col_idx,
insheet.cell_value(row_idx, col_idx))
outrow_idx += 1
wkbk.save(r'C:\combined.xls')
如果你的文件全部有一个标题行,你可能不想重复这一点,所以你可以修改上面的代码看起来更像这样:
firstfile = True # Is this the first sheet?
for f in xlsfiles:
insheet = xlrd.open_workbook(f).sheets()[0]
for row_idx in xrange(0 if firstfile else 1, insheet.nrows):
pass # processing; etc
firstfile = False # We're done with the first sheet.
答案 2 :(得分:4)
当我合并Excel文件(mydata1.xlsx,mydata2.xlsx,mydata3.xlsx)进行数据分析时,这就是我要做的事情:
import pandas as pd
import numpy as np
import glob
all_data = pd.DataFrame()
for f in glob.glob('myfolder/mydata*.xlsx'):
df = pd.read_excel(f)
all_data = all_data.append(df, ignore_index=True)
然后,当我要将其保存为一个文件时:
writer = pd.ExcelWriter('mycollected_data.xlsx', engine='xlsxwriter')
all_data.to_excel(writer, sheet_name='Sheet1')
writer.save()
答案 3 :(得分:2)
仅使用openpyxl
的解决方案(无其他依赖项)。
此脚本应注意将任意数量的xlsx文档合并在一起,无论它们具有一张还是多张图纸。它将保留格式。
有一个功能可以在openpyxl中复制工作表,但是它只能从/到同一文件。在某处还有一个函数insert_rows,但它本身不会插入任何行。因此,恐怕我们一次只能(一次)处理一个牢房。
尽管我不喜欢使用for
循环,而宁愿使用紧凑而优雅的方法(例如列表理解),但由于这是一个副作用,所以我在这里看不到如何做。
在工作簿之间进行复制时要贷记this answer。
#!/usr/bin/env python3
#USAGE
#mergeXLSX.py <a bunch of .xlsx files> ... output.xlsx
#
#where output.xlsx is the unified file
#This works FROM/TO the xlsx format. Libreoffice might help to convert from xls.
#localc --headless --convert-to xlsx somefile.xls
import sys
from copy import copy
from openpyxl import load_workbook,Workbook
def createNewWorkbook(manyWb):
for wb in manyWb:
for sheetName in wb.sheetnames:
o = theOne.create_sheet(sheetName)
safeTitle = o.title
copySheet(wb[sheetName],theOne[safeTitle])
def copySheet(sourceSheet,newSheet):
for row in sourceSheet.rows:
for cell in row:
newCell = newSheet.cell(row=cell.row, column=cell.col_idx,
value= cell.value)
if cell.has_style:
newCell.font = copy(cell.font)
newCell.border = copy(cell.border)
newCell.fill = copy(cell.fill)
newCell.number_format = copy(cell.number_format)
newCell.protection = copy(cell.protection)
newCell.alignment = copy(cell.alignment)
filesInput = sys.argv[1:]
theOneFile = filesInput.pop(-1)
myfriends = [ load_workbook(f) for f in filesInput ]
#try this if you are bored
#myfriends = [ openpyxl.load_workbook(f) for k in range(200) for f in filesInput ]
theOne = Workbook()
del theOne['Sheet'] #We want our new book to be empty. Thanks.
createNewWorkbook(myfriends)
theOne.save(theOneFile)
使用openpyxl 2.5.4,python 3.4进行了测试。
答案 4 :(得分:0)
您可以简单地使用pandas和os库来执行此操作。
import pandas as pd
import os
#create an empty dataframe which will have all the combined data
mergedData = pd.DataFrame()
for files in os.listdir():
#make sure you are only reading excel files
if files.endswith('.xlsx'):
data = pd.read_excel(files, index_col=None)
mergedData = mergedData.append(data)
#move the files to other folder so that it does not process multiple times
os.rename(files, 'path to some other folder')
mergedData DF将具有所有合并的数据,您可以将其导出到单独的excel或csv文件中。相同的代码也可以与csv文件一起使用。只需在中频情况下将其更换
答案 5 :(得分:0)
只需添加到p_barill的答案中,如果您有需要复制的自定义列宽,则可以将以下内容添加到copySheet的底部:
for col in sourceSheet.column_dimensions:
newSheet.column_dimensions[col] = sourceSheet.column_dimensions[col]
我只想在他或她的回答中发表评论,但我的声誉还不够高。