【发布时间】: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!")`
【问题讨论】: