Python openpyxl庫實(shí)現(xiàn)將同一目錄下的excel文件合并為一個(gè)excel功能(包含格式,不含宏),運(yùn)行程序后,輸入要生成的excel文件名稱即可文章來源地址http://www.zghlxwxcb.cn/news/detail-589416.html
import os
import copy
import sys
import openpyxl
from openpyxl.utils import get_column_letter
import win32com.client as win32
#功能目標(biāo):將同目錄下的多個(gè)excel合并到同一個(gè)excel中,sheet頁以excel文件名稱+sheet頁名稱來命名
#-----------------------------
#實(shí)現(xiàn)xls文件轉(zhuǎn)化為xlsx文件
#函數(shù)名稱:xls_to_xlsx(file)
#file xls文件
#------------------------------------------------------------------------------------------
def xls_to_xlsx(file):
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(file)
wb.SaveAs(file + 'x', FileFormat=51) # FileFormat = 51 is for .xlsx extension
wb.Close() # FileFormat = 56 is for .xls extension
excel.Application.Quit()
#------------------------------------------------------------------------------------------
#實(shí)現(xiàn)不同excel文件的sheet頁復(fù)制 全格式復(fù)制
#函數(shù)名稱:sheet copy(source excel,target excel)
#source_excel 源excel文件 target_excel 目標(biāo)excel文件
#將源exce1文件的各個(gè)sheet頁原樣復(fù)制到目標(biāo)excel文件
#------------------------------------------------------------------------------------------
def sheet_copy(source_excel,target_excel):
#判斷源文件和目標(biāo)文件是否為excel文件
if((source_excel.split('.')[1]!='xls' and source_excel.split('.')[1]!='xlsx') or (target_excel.split('.')[1]!='xls' and target_excel.split('.')[1]!='xlsx')):
print('文件類型錯誤,請輸入excel文件類型')
sys.exit()
source_file_name = source_excel.split('.')[0]
wb = openpyxl.load_workbook(source_excel)
#判斷目標(biāo)文件是否存在,不存在創(chuàng)建
if(os.path.isfile(target_excel) == False):
wb2 = openpyxl.Workbook()
wb2.save(target_excel)
wb2 = openpyxl.load_workbook(target_excel)
#獲取源文件的sheet頁名稱 使用文件名+sheet頁名作為目標(biāo)excel文件的sheet頁命名
sheetnames = wb.sheetnames
for sheetname in sheetnames:
print(sheetname)
sheet = wb[sheetname]
sheet2 = wb2.create_sheet(source_file_name+'_'+sheetname)
# tab顏色
sheet2.sheet_properties.tabColor = sheet.sheet_properties.tabColor
# 開始處理合并單元格形式為“(<CellRange A1:A4>,),替換掉(<CellRange 和 >,)' 找到合并單元格
wm = list(sheet.merged_cells)
if len(wm) > 0:
for i in range(0, len(wm)):
cell2 = str(wm[i]).replace('(<CellRange ', '').replace('>,)', '')
sheet2.merge_cells(cell2)
for i, row in enumerate(sheet.iter_rows()):
sheet2.row_dimensions[i + 1].height = sheet.row_dimensions[i + 1].height
for j, cell in enumerate(row):
sheet2.column_dimensions[get_column_letter(j + 1)].width = sheet.column_dimensions[
get_column_letter(j + 1)].width
sheet2.cell(row=i + 1, column=j + 1, value=cell.value)
# 設(shè)置單元格格式
source_cell = sheet.cell(i + 1, j + 1)
target_cell = sheet2.cell(i + 1, j + 1)
target_cell.fill = copy.copy(source_cell.fill)
if source_cell.has_style:
target_cell._style = copy.copy(source_cell._style)
target_cell.font = copy.copy(source_cell.font)
target_cell.border = copy.copy(source_cell.border)
target_cell.fill = copy.copy(source_cell.fill)
target_cell.number_format = copy.copy(source_cell.number_format)
target_cell.protection = copy.copy(source_cell.protection)
target_cell.alignment = copy.copy(source_cell.alignment)
if 'Sheet' in wb2.sheetnames:
del wb2['Sheet']
if(source_excel.split('.')[1]=='xls'):
os.remove(source_excel+'x')
wb2.save(target_excel)
wb.close()
wb2.close()
def main():
path = os.getcwd()
files = os.listdir(path)
if(len(files)==0):
sys.exit()
excel_list = []
for file in files:
if(file.split('.')[1]=='xls'):
xls_to_xlsx(os.path.join(path,file))
files = os.listdir(path)
for file in files:
if (file.split('.')[1] == 'xlsx'):
excel_list.append(file)
print(excel_list)
file_name = input("請輸入最終生成的excel文件名稱")
oneexcel = openpyxl.Workbook()
oneexcel.save(file_name+'.xlsx')
for f in excel_list:
sheet_copy(f,file_name+'.xlsx')
for file in files:
if(file.split('.')[1]=='xls'):
os.remove(file+'x')
if __name__ == '__main__':
main()
文章來源:http://www.zghlxwxcb.cn/news/detail-589416.html
到了這里,關(guān)于多個(gè)excel文件合并為一個(gè)excel的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!