How Do I Use Excel's Format Painter Across a Whole Workbook

馋奶兔 提交于 2019-12-14 02:34:30

问题


Every week I generate a large excel sheet using Python/Pandas. However, the xls writer in Pandas does not allow one to format the excel sheets likely because of the proprietary format. Currently, I have to go worksheet by worksheet in the newly generated file and copy the formatting from the sheet the week before which is a little obnoxious.

Is there a way (in order of preference):

  1. Copy all the formatting from one excel sheet to another in Python
  2. Format Paint all sheets from a workbook to a second workbook
  3. This would be making a sheet with formatting and links which I could update and than resave, but I'm hoping for a solution like (1) or (2).

回答1:


I'd do it that way:

import win32com.client
xlPasteFormats                 = -4122
xlPasteSpecialOperationNone    = -4142
excelInstance = win32com.client.gencache.EnsureDispatch ("Excel.Application")
workbook = excelInstance.Workbooks.Item(1)
worksheet = workbook.Worksheets(1)
worksheet2 = workbook.Worksheets(3)
cells1 = worksheet.UsedRange
cells2 = worksheet2.UsedRange
cells1.Copy()
cells2.PasteSpecial(xlPasteFormats, xlPasteSpecialOperationNone)

which is quite similar to solution in VBA, because uses the same functions, but does it via COM, so you stay completely in Python.

In this code I had workbook open. If you want to open workbook you should put:

filepath = r"path:\To\Excel\Workbook"
excelInstance.Workbooks.Open(filepath)



回答2:


Here is the VBA way to do it (from sancho.s's answer in this question), assuming the sheets in each workbook are named the same. You may be able to use those objects in Python, or at least create this macro in the workbook you copy from.

Sub FormatMAC()
    Dim wb1 As Workbook, wb2 As Workbook
    Set wb1 = Workbooks("Results_2012 - Template - Master.xlsx")
    Set wb2 = Workbooks("Copy of Results_2012 - Template1.xlsm")
    Dim ws1 As Worksheet, ws2 As Worksheet
    For Each ws1 In wb1.Worksheets
      Set ws2 = wb2.Worksheets(ws1.Name)
      ws1.Cells.Copy
      ws2.Cells.PasteSpecial (xlPasteFormats)
    Next ws1
End Sub


来源:https://stackoverflow.com/questions/26044349/how-do-i-use-excels-format-painter-across-a-whole-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!