Python/Pandas从excel sh复制和粘贴

2024-03-28 13:42:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现此语法可从一个工作簿特定的工作表复制和粘贴到另一个工作簿。但是,我需要帮助的是如何将复制的信息粘贴到第二个工作簿/工作表中的特定单元格。我需要把信息粘贴到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是路径2“C:/Users/almur_000/Desktop/disandpopbyage2.xlsx”


Tags: 信息粘贴loadcellxlsxusersdesktopxl
3条回答

谢谢你帮助我。 我稍加修改就找到了答案。我删除了最后一个def语句,并保留了所有其他内容。它工作得很好。复制并粘贴到我需要的位置,而不从模板中删除任何内容。

`#!Python3

-使用OpenPyXl库复制和粘贴范围

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

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

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

因为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

相关问题 更多 >