Python合並Excel表格


 

一、合並路徑下所有后綴xlsx工作薄第一個表格內容

import os
import xlrd
import pandas as pd

#獲取所有需要合並的工作簿路徑,生成list
def file_name(file_dir): 
    list=[]
    for file in os.listdir(file_dir):
        if os.path.splitext(file)[1] == '.xlsx': #選取后綴為xlsx的文件
            list.append(file)
    return list

path = r'C:/Users/xx/Desktop'
wks = file_name(path)

data = []   #定義一個空list
for i in range(len(wks)):
    read_xlsx = xlrd.open_workbook(path + '/' + wks[i])
    sheet1 = read_xlsx.sheets()[0] #查看sheet1的數據
    nrow =  sheet1.nrows
    for j in range(0,nrow): #逐行打印
        data.append(sheet1.row_values(j))

content= pd.DataFrame(data)

#寫入文件
#寫入csv文件
#content.to_csv(path+'\\py_union.xlsx', sep=',', header=True, index=False)
#寫入excel文件
content.to_excel(path+'\\py_union.xlsx', header=False, index=False)
合並工作簿

 

二、合並單個工作簿的所有表格內容(包括合並單元格)

import os
import xlrd
import pandas as pd


data = []
path = r'C:/Users/xx/Desktop/測試題_0716.xlsx'
xlsx = xlrd.open_workbook(path)
for i in xlsx.sheet_names():
    sheet = xlsx.sheet_by_name(i)
    nrow = sheet.nrows
    for j in range(0,nrow):
        data.append(sheet.row_values(j))

content= pd.DataFrame(data)
content.to_excel('C:/Users/xx/Desktop/py_union.xlsx', header=False, index=False)
合並工作表
import os
import pands as pd


df=pd.read_excel()
sheet_name = ['detail' + str(i) for i in range(1,4)]
data_all = pd.DataFrame()
for i in sheet_name:
    data = pd.read_excel('',encoding='gbk',sheet_name=i,dtype={'id':str})
    data_all = pd.concat([data_all,data],axis=0,ignore_index=True)
data_all.to_csv('csv',index=False,encoding='utf-8')
pandas合並工作簿的工作表

 os.getcwd()獲取當前路徑 os.chdir('')修改當前路徑

三、對合並單元格的研究

xlsx格式不支持xlrd的formatting=True

xlsx = xlrd.open_workbook(path)

table = xlsx.sheet_by_name(xlsx.sheet_names()[1])

merge = table.merged_cells

colspan={}

for item in merge:
  colspan.update({(item[0],item[2]):table.cell_value(item[0],item[2])})

簡單將工作表內的合並單元格取出

四、xlrd函數詳解

https://www.cnblogs.com/insane-Mr-Li/p/9092619.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM