如何连接3个过人之处文件XLSX使用Python?(How to concatenate three

2019-08-19 07:17发布

你好,我想以连接3个过人之处文件XLSX使用python。

我一直在使用openpyxl试过,但我不知道哪个功能可以帮助我三个工作表追加到一个。

你有什么想法如何做到这一点?

非常感谢

Answer 1:

这里有一个熊猫为基础的方法。 (它使用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)


Answer 2:

我会用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.


Answer 3:

当我结合对数据进行分析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()


Answer 4:

解决方案与openpyxl只(不一堆其他相关性)。

这个脚本应该照顾都融合在一起的xlsx文件任意数量的,他们是否有一个或多个工作表。 它将保留格式。

有一个在openpyxl复制表的功能,但它只是从/到同一个文件。 还有一个功能INSERT_ROWS地方,但它本身不插入任何行。 所以,恐怕我们还是要应付(繁琐),并以每次一个单元。

虽然我不喜欢使用for循环,而宁愿使用一些小巧精美的喜欢列表理解,我不知道该怎么做,在这里,因为这是一个副作用秀。

感谢这个答案在工作簿之间复制。

#!/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,蟒蛇3.4。



Answer 5:

你可以简单地使用熊猫和操作系统资源做到这一点。

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文件正常工作。 刚刚取代它在IF条件



文章来源: How to concatenate three excels files xlsx using python?