办公自动化 Python 对Excel不同的sheet合并到一个文件中。

在工作过程中,常遇到不同的sheet存储着一样格式的数据,比如每个月份都有1个Sheet,当对整年进行数据分析时,需要对同一个表格中的所有sheet数据进行合并,再进行分析。为提高我们的工作效率,可以使用python 的xlwings库文件对Excel进行操作,瞬间完成同一个表格所有sheet的合并,具体实现的代码如下:

# -*- coding: utf-8 -*-
"""
Created on Sun Jan 31 15:12:24 2021

@author: lam
"""


def mgSheet(inputfilename,outputfilename):
    import xlwings as xw      
    app = xw.App(visible=False)    
    wb = xw.Book(inputfilename)    
    sths = wb.sheets  
    data = []   
    for sth in sths:
        if sth.range('A1').value:
            print(sth)
            values = sth.range('A2').expand().value
            if isinstance(values[0],str):
                data += [values]
            else:
                data += values
                
    wb_new = xw.Book()
    sth_new = wb_new.sheets[0]
    last_column = sths[0].used_range.last_cell.column    
    sth_new.range('A1').value = sths[0].range('1:'+str(last_column)).value    
    sth_new.range('A2').value = data    
    wb_new.save(outputfilename)
    wb.close()
    wb_new.close()
    import os   
    path = os.path.join(os.path.dirname(__file__) , outputfilename)
   app.quit()
    print(path,':end!')

if __name__=='__main__':
    print('start.....')
    inputfilename =r'.\filename\测试表.xlsx'
    outputfilename =r'合并.xlsx'
    mgSheet(inputfilename,outputfilename)

你可能感兴趣的:(办公自动化 Python 对Excel不同的sheet合并到一个文件中。)