简体   繁体   中英

Python/Pandas copy and paste from excel sheet

I found this syntax to copy and paste from one workbook specific sheet to another workbook. however, what i need help with is how to paste the copied information to a specific cell in the second workbook/sheet. like i need to information to be pasted in cell B3 instead of A1. Thank you

import openpyxl as xl
path1 = "C:/Users/almur_000/Desktop/disandpopbyage.xlsx"
path2 = "C:/Users/almur_000/Desktop/disandpopbyage2.xlsx"
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]
wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.create_sheet(ws1.title)
for row in ws1:
    for cell in row:
        ws2[cell.coordinate].value = cell.value
wb2.save(path2)

wb2 is path2 "C:/Users/almur_000/Desktop/disandpopbyage2.xlsx"

Since the OP is using the openpyxl module I wanted to show a way to do this using that module. With this answer I demonstrate a way to move the original data to new column and row coordinates (there may be better ways to do this).

This fully reproducible example first creates a workbook for demonstration purposes called 'test.xlsx', with three sheets named 'test_1', 'test_2' and 'test_3'. Then using openpyxl , it copies 'test_2' into a new workbook called 'new.xlsx' shifting the cells over 4 columns and down 3 columns. It makes use of the ord() and chr() functions.

import pandas as pd
import numpy as np
import openpyxl

# This section is sample code that creates a worbook in the current directory with 3 worksheets
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='test_1', index=False)
df.to_excel(writer, sheet_name='test_2', index=False)
df.to_excel(writer, sheet_name='test_3', index=False)
wb  = writer.book
ws = writer.sheets['test_2']
writer.close()
# End of sample code that creates a worbook in the current directory with 3 worksheets

wb = openpyxl.load_workbook('test.xlsx')
ws_name_wanted = "test_2"
list_all_ws = wb.get_sheet_names()
for item in list_all_ws:
    if item != ws_name_wanted:
        remove = wb.get_sheet_by_name(item)
        wb.remove_sheet(remove)
ws = wb['%s' % (ws_name_wanted)]
for row in ws.iter_rows():
    for cell in row:
        cell_value = cell.value
        new_col_loc = (chr(int(ord(cell.coordinate[0:1])) + 4))
        new_row_loc = cell.coordinate[1:]
        ws['%s%d' % (new_col_loc ,int(new_row_loc) + 3)] = cell_value
        ws['%s' % (cell.coordinate)] = ' '

 wb.save("new.xlsx")

Here's what 'test.xlsx' looks like:

test.xlsx的预期输出

And here's what 'new.xlsx' looks like:

new.xlsx的预期输出

thank you for those helping me. I found the answer with slight modification. I have removed the last def statement and kept every thing else as it is. it works fantastically. copy and paste in the place i need without removing anything from the template.

`#! Python 3

- Copy and Paste Ranges using OpenPyXl library

import openpyxl

#Prepare the spreadsheets to copy from and paste too.

#File to be copied
wb = openpyxl.load_workbook("foo.xlsx") #Add file name
sheet = wb.get_sheet_by_name("foo") #Add Sheet name

#File to be pasted into
template = openpyxl.load_workbook("foo2.xlsx") #Add file name
temp_sheet = template.get_sheet_by_name("foo2") #Add Sheet name

#Copy range of cells as a nested list
#Takes: start cell, end cell, and sheet you want to copy from.
def copyRange(startCol, startRow, endCol, endRow, sheet):
    rangeSelected = []
    #Loops through selected Rows
    for i in range(startRow,endRow + 1,1):
        #Appends the row to a RowSelected list
        rowSelected = []
        for j in range(startCol,endCol+1,1):
            rowSelected.append(sheet.cell(row = i, column = j).value)
        #Adds the RowSelected List and nests inside the rangeSelected
        rangeSelected.append(rowSelected)

    return rangeSelected


#Paste range
#Paste data from copyRange into template sheet
def pasteRange(startCol, startRow, endCol, endRow, sheetReceiving,copiedData):
    countRow = 0
    for i in range(startRow,endRow+1,1):
        countCol = 0
        for j in range(startCol,endCol+1,1):

            sheetReceiving.cell(row = i, column = j).value = copiedData[countRow][countCol]
            countCol += 1
        countRow += 1
def createData():
    print("Processing...")
    selectedRange = copyRange(1,2,4,14,sheet) #Change the 4 number values
    pastingRange = pasteRange(1,3,4,15,temp_sheet,selectedRange) #Change the 4 number values
    #You can save the template as another file to create a new file here too.s
    template.save("foo.xlsx")
    print("Range copied and pasted!")`

To copy paste the entire sheet from work book to another.

import pandas as pd

#change NameOfTheSheet with the sheet name that includes the data
data = pd.read_excel(path1, sheet_name="NameOfTheSheet")

#save it to the 'NewSheet' in destfile
data.to_excel(path2, sheet_name='NewSheet')

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