【问题标题】:Python script to copy-paste range of cells in Excel files用于复制粘贴 Excel 文件中的单元格范围的 Python 脚本
【发布时间】:2021-09-20 03:53:08
【问题描述】:

我正在尝试从一个 Excel 文件中复制从单元格 A2 开始的一系列列并粘贴到另一个 Excel 文件中。当我运行脚本时,我没有收到任何错误,但没有任何反应。我注意到的一件事是,在 Notepadd++ 中,某些代码似乎没有像应有的那样突出显示,例如 wb= openpyxl.load_workbook 只是纯文本,不像文件中的其他一些操作那样染成蓝色,不确定如果这导致了我的问题。这是我正在使用的代码:

`#!蟒蛇 3 # - 使用 OpenPyXl 库复制和粘贴范围

import openpyxl

#Prepare the spreadsheets to copy from and paste too.

 

#File to be copied
wb = openpyxl.load_workbook("Current_Comments.xlsx") #Add file name
sheet = wb["Sheet1"] #Add Sheet name

#File to be pasted into
template = openpyxl.load_workbook("Current_Comments2.xlsx") #Add file 
name
temp_sheet = template["Sheet1"] #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,19,7500,sheet) #Change the 4 number values
    pastingRange = pasteRange(1,2,19,7500,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!")` 

【问题讨论】:

    标签: python excel


    【解决方案1】:

    尝试删除 createData() 并运行其中的代码,而不是函数。

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    相关资源
    最近更新 更多