简体   繁体   中英

How to copy one excel sheet template into multiple excel files using python

i am trying to copy an excel spreadsheet which has some text and numbers and a logo image into multiple excel files as a new sheet with source formatting using python, any help is greatly appreciated.

It's not clear what your end requirement and restrictions are. The basic requirement; "I am trying to copy an excel spreadsheet which has some text and numbers and a logo image into multiple excel files" just indicates you want multiple copies of the same Excel file, the File Management app of your OS can do this, with the limitation perhaps being the resultant naming of each file. If this is your requirement then perhaps something like Python - making copies of a file may help to create the files with the necessary naming.

If its a workbook with multiple sheets and you only want one sheet copied to new workbooks then openpyxl can help. Copying sheets is easy enough however the formatting requires extra code. If there is just a couple of sheets in the original it may be easier to just remove those sheets before saving your copy, see example code below. Otherwise this link may help How to copy worksheet from one workbook to another one using openpyxl?

Example: The following code shows how to open an existing workbook, 'templateA.xlsx' which has two sheets, 'Sheet1 & 'Sheet2'. You only want 'Sheet1' saved as multiple copies (10) named 'template1.xlsx', 'template2.xlsx', 'template3.xlsx'... The code open the original workook, deletes the sheet called 'Sheet2' before making 10 copies.

from openpyxl import load_workbook

# Load the original Excel workbook
wb = load_workbook("templateA.xlsx")

# delete the Sheet2 that is not required
del wb["Sheet2"]

# Save 10 copies of the workbook with Sheet1 only
for i in range(10):
    wb.save("template" + str(i) + ".xlsx")

The first link python-making-copies-of-a-file can help if your required naming is more complex than the example given.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM