Python Forum
Why can't I copy and past only ONE specific tab?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why can't I copy and past only ONE specific tab?
#1
Hello,
This is my first post, be gentle. :)

I am an expert Excel user who is now venturing into Python in an effort to automate "the boring stuff".

That said, I have what is probably a very basic question, however, I have come to a dead end. Via Python (openpyxl) I would like to cut and paste (values only) one specific tab into a new Excel file. The code I am using below works well in terms of only pasting values and preserving formatting. The downfall is it copies ALL the tabs of the source file.
I am calling out the desired tab name that I am trying to copy ('10_Yr') in line five of said code (shown below), however, it doesn't seem to work. How can I specify only the exact tab(s) that I want to copy? Every search and tutorial that I encounter somehow doesn't address this. Many thanks in advance.


from openpyxl import load_workbook
from copy import copy

wb = load_workbook(r"C:\Original File Name.xlsx", data_only = True)   #your file name
ws = wb['10_Yr'] #your sheet name in the file above

for group in list(ws.merged_cells.ranges):
    min_col, min_row, max_col, max_row = group.bounds
    cell_start = ws.cell(row = min_row, column = min_col)
    top_left_cell_value = cell_start.value

    ws.unmerge_cells(str(group))

    for i_row in range(min_row, max_row + 1):
        for j_col in range(min_col, max_col + 1): 
            ws.cell(row = i_row, column = j_col, value = top_left_cell_value)
            #copy the cell format
            ws.cell(row = i_row, column = j_col).alignment = copy(cell_start.alignment)
            ws.cell(row = i_row, column = j_col).border = copy(cell_start.border)
            ws.cell(row = i_row, column = j_col).font = copy(cell_start.font)

wb.save(r"C:\new file name.xlsx")
Reply
#2
I don't see where you create a new workbook.
Reply
#3
(Jan-10-2024, 06:37 PM)deanhystad Wrote: I don't see where you create a new workbook.

The last line creates the new workbook. It may be a bit unorthodox but it works on my end.
Reply
#4
No, the last line writes the existing workbook to a new file. Nowhere do you create a new workbook. You'll want to create a new workbook object, create your new "tab" in the new workbook, then write the new workbook to a file.
Reply
#5
You need a source file and a target file. I never dabbled with unmerging cells.

Something like this:

import openpyxl

# the folder with the XL file
path2XL = '/home/pedro/myPython/openpyxl/xlsx_files/Delta_blanko.xlsx'
savepath = '/home/pedro/myPython/openpyxl/xlsx_files/Delta_blanko_changed.xlsx'
sourceFile = openpyxl.load_workbook(path2XL)
sourceSheetNames = sourceFile.sheetnames
for sheet in sourceSheetNames:
    print('This XL has the sheets:', sheet)

sFsheet = input('Copy and paste the name of the sheet you want to copy.')
# create a target file
targetFile = openpyxl.Workbook()
# a new file has 1 sheet called Sheet
targetFileSheetNames = targetFile.sheetnames
ts = targetFile.active
# rename the sheet Sheet to anything you like
ts.title = 'My shiny new sheet'
count = 1
for row in sourceFile[sFsheet].values:
    print(row)
    for i in range(len(row)):
        targetFile['My shiny new sheet'].cell(row=count, column=i+1).value=row[i]
    count+=1

targetFile.save(savepath)
Of course, there are other ways to achieve this, especially if you only want specific columns and/or rows.
Reply
#6
Thank you for replying...I don't get any errors, but a new file is not produced when running that code. Nothing shows up in the targeted folder (or any folder).

Here is a recap of what I tried:

import openpyxl
 
# the folder with the XL file
path2XL = r'C:\Source_File.xlsx'
savepath = r'C:\New_File_Name.xlsx'
sourceFile = openpyxl.load_workbook(path2XL)
sourceSheetNames = sourceFile.sheetnames
for sheet in sourceSheetNames:
    print(r'C:\Source_File.xlsx', sheet)
 
sFsheet = input('Source File Sheet Name')
# create a target file
targetFile = openpyxl.Workbook()
# a new file has 1 sheet called Sheet
targetFileSheetNames = targetFile.sheetnames
ts = targetFile.active
# rename the sheet Sheet to anything you like
ts.title = 'New Name for Sheet'
count = 1
for row in sourceFile[sFsheet].values:
    print(row)
    for i in range(len(row)):
        targetFile['New Name for Sheet'].cell(row=count, column=i+1).value=row[i]
    count+=1
 
targetFile.save(savepath)
deanhystad write Jan-12-2024, 02:42 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#7
The only thing I can think of is that you are not allowed to create files in C:? This code works fine for me. The steps are the same used in your program.
"""Copy sheet from existing spreadsheet to a new file."""

import openpyxl
from pathlib import Path

path = Path("./spreadsheets")  # Where to find spreadsheet files

# Open the existing spreadsheet file and get the worksheet to copy.
source_wb = openpyxl.load_workbook(path / "test.xlsx")
source = source_wb["Sheet1"]

# Make a new workbook and rename the first worksheet.
wb = openpyxl.Workbook()
target = wb[wb.sheetnames[0]]
target.title = "Source File Sheet Name"

# Copy values from source to target.
for row, row_values in enumerate(source.values, start=1):
    for column, value in enumerate(row_values, start=1):
        target.cell(row=row, column=column, value=value)

# Save copy
wb.save(path / "copy.xlsx")
Reply
#8
Thanks, I actually got it work. There was a problem with my path where the file was saved (my oversight).
The only caveat is only hard-coded values are pasted into the new file, tab, etc.
Is there a way to amend where formulas would be captured and pasted as values?
Many thanks again.
Reply
#9
I do not understand your question. Please elaborate.

This may answer some of your questions.

https://stackoverflow.com/questions/4234...g-openpyxl
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 287 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  Need to run 100+ Chrome’s with Selenium but can’t get past ~15 without breaking imillz 0 1,370 Sep-04-2021, 04:51 PM
Last Post: imillz
  Struggling for the past hour to define function and call it back godlyredwall 2 2,233 Oct-29-2020, 02:45 PM
Last Post: deanhystad
  Delete specific lines contain specific words mannyi 2 4,148 Nov-04-2019, 04:50 PM
Last Post: mannyi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020