如何使用python连接三个excels文件xlsx? [英] How to concatenate three excels files xlsx using python?

查看:222
本文介绍了如何使用python连接三个excels文件xlsx?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我想使用python连接三个excels文件xlsx。



我已经尝试使用openpyxl,但是我不知道哪个函数可以帮助我添加三个工作表一个。



你有什么想法吗?



非常感谢我将使用 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
在xlsfiles中的f:
#这都是未经测试的;基本上只是伪代码的概念!
insheet = xlrd.open_workbook(f).sheets()[0] xrange(insheet.nrows)中row_idx的
:xrange(insheet.ncols)中col_idx的

outsheet.write(outrow_idx,col_idx,
insheet.cell_value(row_idx,col_idx))
outrow_idx + = 1
wkbk.save(r'C:\combined.xls')

如果您的文件全部有一个标题行,你可能不想重复一遍,所以你可以修改上面的代码看起来更像这样:

  firstfile = True#这是第一张? 
for x 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#我们完成了第一张表。


Hello I would like to concatenate three excels files xlsx using python.

I have tried using openpyxl, but I don't know which function could help me to append three worksheet into one.

Do you have any ideas how to do that ?

Thanks a lot

解决方案

I'd use xlrd and xlwt. Assuming you literally just need to append these files (rather than doing any real work on them), I'd do something like: Open up a file to write to with xlwt, and then for each of your other three files, loop over the data and add each row to the output file. To get you started:

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')

If your files all have a header line, you probably don't want to repeat that, so you could modify the code above to look more like this:

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.

这篇关于如何使用python连接三个excels文件xlsx?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆