主頁 > 知識庫 > python openpyxl 帶格式復制表格的實現(xiàn)

python openpyxl 帶格式復制表格的實現(xiàn)

熱門標簽:百度AI接口 客戶服務 企業(yè)做大做強 語音系統(tǒng) Win7旗艦版 硅谷的囚徒呼叫中心 呼叫中心市場需求 電話運營中心

有合并單元格的,先把合并單元格復制過去,合并單元格用wm=list(zip(wbsheet.merged_cells))得出合并單元格列表,把其中的(CellRange A1:A4>,) 替換成為A1:A4格式

再從新表中合并單元格

再用.has_style: #拷貝格式 測試是否有格式,再復制格式和數(shù)據(jù)

其中:

font(字體類):字號、字體顏色、下劃線等

fill(填充類):顏色等

border(邊框類):設置單元格邊框

alignment(位置類):對齊方式

number_format(格式類):數(shù)據(jù)格式

protection(保護類):寫保護

import os							#找文件目錄
import win32com.client as win32 	#操作excel文件
from tqdm import tqdm 				#進度條顯示
from openpyxl import load_workbook # 讀取時導入這個
from openpyxl.styles import Font, Alignment #設置單元格格式
from openpyxl.utils import get_column_letter, column_index_from_string
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
from copy import copy
path=input('輸入整理前原始路徑: ')
if path=="":
	path=os.getcwd()
xlsx_lists=[]
xls_lists=[]
for file in os.listdir(path):
 filename=os.path.join(path,file)
 if os.path.isfile(filename):    #是目錄
  if filename.endswith(".xls"):
  	xls_lists.append(filename)
  if filename.endswith(".xlsx"):
  	xlsx_lists.append(filename)
source_file='原始數(shù)據(jù).xlsx'
if os.path.exists(os.path.join(os.getcwd(),source_file)):
	os.remove(os.path.join(os.getcwd(),source_file))
choose="1"
excel = win32.gencache.EnsureDispatch('Excel.Application')
# while choose not in "1|2":
#  choose =input("xls轉為xlsx:1 xlsx轉為xls:2 ")
if choose=="1":
	with tqdm(total=len(xls_lists),desc='寫文件數(shù) ',leave=True,unit='個',unit_scale=True,mininterval=0.5,bar_format=None) as pbar:
		for xls_list in xls_lists:
			pbar.update(1)
			wb = excel.Workbooks.Open(xls_list)
			wb.SaveAs(xls_list+"x", FileFormat = 51) #FileFormat = 51 is for .xlsx extension
			wb.Close()        #FileFormat = 56 is for .xls extension
		pbar.close()
else:
	with tqdm(total=len(xls_lists),desc='寫文件數(shù) ',leave=True,unit='個',unit_scale=True,mininterval=0.5,bar_format=None) as pbar:
		for xlsx_list in xlsx_lists:
			pbar.update(1)
			wb = excel.Workbooks.Open(xlsx_list)
			wb.SaveAs(xlsx_list[0:len(xlsx_list)-1], FileFormat = 56) #FileFormat = 51 is for .xlsx extension
			wb.Close() 
		pbar.close()
excel.Application.Quit()
tag_file='拆分后表.xlsx'
totaldata=pd.DataFrame()
writer=pd.ExcelWriter(tag_file)
totaldata.to_excel(writer, 'sheet')
writer.save()
book = load_workbook(tag_file)   #能寫入已存在表中
wb = load_workbook('原始數(shù)據(jù).xlsx')
for sheet in wb.sheetnames:
	print(sheet)
	wbsheet=wb[sheet]
	for num in range(3):
		name=wbsheet.cell(1,num*15+10).value
		wbsheet_new = book.create_sheet(name,0)
		wm=list(wbsheet.merged_cells) #開始處理合并單元格形式為“(CellRange A1:A4>,),替換掉(CellRange 和 >,)' 找到合并單元格
		#print (list(wm))
		if len(wm)>0 :
			for i in range(0,len(wm)):
				cell2=str(wm[i]).replace('(CellRange ','').replace('>,)','')
				#print("MergeCell : %s" % cell2)
				wbsheet_new.merge_cells(cell2)
		for rows in range(40):
			wbsheet_new.row_dimensions[rows+1].height = wbsheet.row_dimensions[rows+1].height 
			for col in range(14):
				wbsheet_new.column_dimensions[get_column_letter(col+1)].width = wbsheet.column_dimensions[get_column_letter(col+1)].width
				wbsheet_new.cell(row=rows+1,column=col+1,value=wbsheet.cell(rows+1,num*15+col+1).value)
				if wbsheet.cell(rows+1,num*15+col+1).has_style:	#拷貝格式
					wbsheet_new.cell(row=rows+1,column=col+1).font = copy(wbsheet.cell(rows+1,num*15+col+1).font)
					wbsheet_new.cell(row=rows+1,column=col+1).border = copy(wbsheet.cell(rows+1,num*15+col+1).border)
					wbsheet_new.cell(row=rows+1,column=col+1).fill = copy(wbsheet.cell(rows+1,num*15+col+1).fill)
					wbsheet_new.cell(row=rows+1,column=col+1).number_format = copy(wbsheet.cell(rows+1,num*15+col+1).number_format)
					wbsheet_new.cell(row=rows+1,column=col+1).protection = copy(wbsheet.cell(rows+1,num*15+col+1).protection)
					wbsheet_new.cell(row=rows+1,column=col+1).alignment = copy(wbsheet.cell(rows+1,num*15+col+1).alignment)
wb.close()
book.save('拆分后表.xlsx')
book.close()

上例中,因為要把一個表拆分為三個,所以要循環(huán)三次

補充:python-excel 之帶有格式及合并單元格樣式的表格復制

代碼如下:

from openpyxl import load_workbook
 
 
def copy_excel(totle_excel,totle_sheetname,down_excel,down_sheetname):
 down = load_workbook(down_excel)
 totle = load_workbook(totle_excel)
 totle_sheet = totle[totle_sheetname]
 down_sheet = down[down_sheetname]
 # 兩個for循環(huán)遍歷整個excel的單元格內容
 for i, row in enumerate(down_sheet.iter_rows()):
  for j, cell in enumerate(row):
   totle_sheet.cell(row=i + 1, column=j + 1, value=cell.value)
 totle.save(totle_excel)

代碼說明:

文件內容是從down_excel的down_sheetname復制到totle_excel的totle_sheetname

說明:

以上代碼可以將格式以及合并單元格的樣式均復制到另一張表

注意:

如果你是跨excel文件的復制且?guī)в泄?,不建議使用

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

您可能感興趣的文章:
  • python 辦公自動化——基于pyqt5和openpyxl統(tǒng)計符合要求的名單
  • Python Excel處理庫openpyxl詳解
  • python使用openpyxl庫讀寫Excel表格的方法(增刪改查操作)
  • Python利器openpyxl之操作excel表格
  • Python離線安裝openpyxl模塊的步驟
  • 解決python 使用openpyxl讀寫大文件的坑
  • Python openpyxl 無法保存文件的解決方案
  • python 使用openpyxl讀取excel數(shù)據(jù)
  • python openpyxl的使用方法

標簽:長沙 喀什 山西 崇左 濟南 海南 山西 安康

巨人網(wǎng)絡通訊聲明:本文標題《python openpyxl 帶格式復制表格的實現(xiàn)》,本文關鍵詞  ;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266