使用Python + Openpyxl在Excel中将一张纸难于复制和粘贴到另一张纸

时间:2019-04-17 15:23:43

标签: python openpyxl

我正在尝试编写可在一个Excel电子表格(first_sheet)中的单元格中查找与字典中的单词(second_sheet)相匹配的单词的代码。如果有匹配项,我想将该单元格复制并粘贴到第三个电子表格(输出)中。我在复制和粘贴代码部分时遇到困难。任何人都可以看看+提供一些反馈吗?

我编写的代码可以识别字典中的单词,但是我编写的用于复制+粘贴到输出电子表格中的代码似乎无法正常工作。我没有收到错误消息。输出电子表格只是空的。我花了三天时间遍历代码,以查看问题出在哪里,但仍然无法解决问题。有没有人?

# create dictionary of words to search for
Dict = {}
    for row in range(1, dictionary.max_row+1):
    for col in range(1, 2):
    cell_value = dictionary.cell(row=row, column=col).value
    Dict[cell_value] = dictionary.cell(row=row, column=1).value
    print (dictionary.cell(row=row, column=col).value)

global newRow
newRow = 1

# Search through worksheet with items from dictionary. If dictionary item is found, copy and paste row to separate sheet.
for row in range(1, data.max_row + 1):
    for col in range(1, 2):
        cell_value = data.cell(row=row, column=col).value
        if cell_value in Dict:
            print (data.cell(row=row, column=col).value)
        # Copy range of cells as a  list
        # Takes: start cell, end cell, and sheet you want to copy from.
            def copyRange(selectRow, selectColumn, data):
                rangeSelected = []
                rangeSelected.append(cell_value)
                print("copy works")
                return rangeSelected

        # Paste range
        # Paste data from copyRange into template sheet
            def pasteRange(pasteRow, pasteColumn, output, copiedData):
                global newRow
                countRow = 0
                countColumn = 0
                output.cell(row= newRow, column=1).value = copiedData[countRow][countColumn]
                newRow += 1
                print("paste works")

            def createData():
                global newRow
                print("Processing...")
                selectedRange = copyRange(row, 1, data) #Change the 4 number values
                print("range")
                pasteRange(newRow, 1, output, selectedRange)
            #Change the 4 number values
            #You can save the template as another file to create a new file here too
                print ("Copy and pasted.")

            createData()

wb.save('campaigns_practicefile.xlsx')
print ("save works")

0 个答案:

没有答案