美文网首页PythonPython_办公自动化
Python实用-Excel批量合并

Python实用-Excel批量合并

作者: 小由读书 | 来源:发表于2021-12-11 13:58 被阅读0次

    需求:将多个Excel中的内容汇总合并成一个文件

    涉及内容:

    1.python扩展库:xlrd(读取Excel文件)、xlwt(写入Excel文件)

    2.python读取Excel文件

    import xlrd

    file = 'D:\\hhh\\a.xls'

    data= xlrd.open_workbook(file)

    table = data.sheet()[0]

    value = table.cell_value(rowx =4,colx=4)

    3.python写入Excel文件

    import xlwt

    #指定合并完成的路径

    dst_file= 'D:\\111\\re.xls'

    workbook= xlwt.Workbook(encoding='utf-8')

    xlsheet= workbook.add_sheet('结果')

    #写入内容为value

    xlsheet.write(0,0,value)

    #保存文件

    workbook.save(dst_file)

    4.需求实现完整代码(55行):

    import xlrd

    import xlwt

    from pathlibimport Path,PurePath

    #指定要合并的Excel路径

    src_path= 'D:\\hhh'

    #指定合并完成的路径

    dst_file= 'D:\\111\\re.xls'

    #取得该目录下所有xls格式结尾的文件

    p= Path(src_path)

    files= []

    for xin p.iterdir():

        if PurePath(x).match('*.xls'):

            files.append(x)

    #准备一个列表存放读取结果

    content= []

    #对每个文件进行重复处理

    for filein files:

        username= file.stem

    data= xlrd.open_workbook(file)

        table= data.sheets()[0]

        line1= table.cell_value(rowx= 0,colx=0)

        line2= table.cell_value(rowx=1, colx=1)

        temp= f'{username},{line1},{line2}'

        #合并成一行存储起来

        content.append(temp.split(','))

        print(temp)

    #写入表头

    table_header= ['姓名','1行1列','2行2列']

    workbook= xlwt.Workbook(encoding='utf-8')

    xlsheet= workbook.add_sheet('结果')

    row=0

    col=0

    for cell_headerin table_header:

        xlsheet.write(row,col,cell_header)

        col+= 1

    #向下移动一行

    row+= 1

    #取出每一行内容

    for linein content:

        col= 0

        #取出每个单元格内容

        for cellin line:

            #写入内容

            xlsheet.write(row,col,cell)

            #向右移动一个单元格

            col+= 1

        #向下移动一行

        row+= 1

    workbook.save(dst_file)

    相关文章

      网友评论

        本文标题:Python实用-Excel批量合并

        本文链接:https://www.haomeiwen.com/subject/pgukfrtx.html