Python / Pandas从excel表复制和粘贴

问题描述 投票:1回答:3

我发现这种语法从一个工作簿特定工作表复制并粘贴到另一个工作簿。但是,我需要帮助的是如何将复制的信息粘贴到第二个工作簿/表中的特定单元格。就像我需要将信息粘贴在单元格B3而不是A1中。谢谢

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是path2“C:/Users/almur_000/Desktop/disandpopbyage2.xlsx”

python excel openpyxl
3个回答
1
投票

由于OP使用openpyxl模块,我想展示一种使用该模块的方法。通过这个答案,我演示了一种将原始数据移动到新的列和行坐标的方法(可能有更好的方法来执行此操作)。

这个完全可重现的示例首先创建一个用于演示目的的工作簿,称为“test.xlsx”,其中包含三个名为“test_1”,“test_2”和“test_3”的工作表。然后使用openpyxl,它将'test_2'复制到一个名为'new.xlsx'的新工作簿中,将单元格移到4列和3列。它利用了ord()chr()函数。

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")

这是'test.xlsx'的样子:

Expected Output of test.xlsx

这就是'new.xlsx'的样子:

Expected Output of new.xlsx


1
投票

谢谢那些帮助我的人。我稍微修改了一下答案。我删除了最后一个def语句并保留了其他所有内容。它非常有效。复制并粘贴到我需要的地方,而不从模板中删除任何内容。

`#! 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!")`

0
投票

复制将整个工作表从工作簿粘贴到另一个工作簿。

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')
© www.soinside.com 2019 - 2024. All rights reserved.