溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python如何使用openpyxl復制整張sheet

發(fā)布時間:2021-03-19 14:01:29 來源:億速云 閱讀:973 作者:小新 欄目:開發(fā)技術

這篇文章將為大家詳細講解有關Python如何使用openpyxl復制整張sheet,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

通過無能的baidu逛了一圈,發(fā)現(xiàn)有兩三段能用的代碼,不過參考之下,發(fā)現(xiàn)還有不足的:

不能拷貝有合并格式的sheet、沒有拷貝cell的相關格式(填充、邊框、對齊)等參數(shù)

所以通過bing繼續(xù)發(fā)掘,最終合成以下代碼:

from copy import copy
from openpyxl import load_workbook, Workbook
 
def replace_xls(src_file,tag_file,sheet_name):
 
#    src_file是源xlsx文件,tag_file是目標xlsx文件,sheet_name是目標xlsx里的新sheet名稱
 
 print("Start sheet %s copy from %s to %s"%(sheet_name,src_file,tag_file))
 wb = load_workbook(src_file)
 wb2 = load_workbook(tag_file)
 
 ws = wb.get_sheet_by_name(wb.get_sheet_names()[0])
 ws2 = wb2.create_sheet(sheet_name.decode('utf-8'))
 
 max_row=ws.max_row  #最大行數(shù)
 max_column=ws.max_column  #最大列數(shù)
 
 wm=zip(ws.merged_cells) #開始處理合并單元格
 if len(wm)>0 :
 for i in range(0,len(wm)):
  cell2=str(wm[i]).replace('(<MergeCell ','').replace('>,)','')
  print("MergeCell : %s" % cell2)
  ws2.merge_cells(cell2)
 
 for m in range(1,max_row + 1):
 ws2.row_dimensions[m].height = ws.row_dimensions[m].height 
 for n in range(1,1 + max_column):
  if n<27 :
  c=chr(n+64).upper() #ASCII字符,chr(65)='A'
  else:
  if n < 677 :
   c=chr(divmod(n,26)[0]+64)+chr(divmod(n,26)[1]+64)
  else:
   c=chr(divmod(n,676)[0]+64) + chr(divmod(divmod(n,676)[1],26)[0]+64) + chr(divmod(divmod(n,676)[1],26)[1]+64)
  i='%s%d'%(c,m) #單元格編號
  if m == 1 :
#   print("Modify column %s width from %d to %d" % (n, ws2.column_dimensions[c].width ,ws.column_dimensions[c].width))
   ws2.column_dimensions[c].width = ws.column_dimensions[c].width
  try:
  getattr(ws.cell(row=m, column=c), "value" )
  cell1=ws[i]  #獲取data單元格數(shù)據(jù)
  ws2[i].value=cell1.value  #賦值到ws2單元格
  if cell1.has_style: #拷貝格式
   ws2[i].font = copy(cell1.font)
   ws2[i].border = copy(cell1.border)
   ws2[i].fill = copy(cell1.fill)
   ws2[i].number_format = copy(cell1.number_format)
   ws2[i].protection = copy(cell1.protection)
   ws2[i].alignment = copy(cell1.alignment)
  except AttributeError as e:
  print("cell(%s) is %s" % (i,e))
  continue
 
 wb2.save(tag_file)
 
 wb2.close()
 wb.close()

關于“Python如何使用openpyxl復制整張sheet”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI