将数据从一个Excel文件复制到另一个范围和图形问题

时间:2018-08-09 08:45:59

标签: python excel openpyxl

我有一个python代码可以将数据从一个excel文件复制到另一个文件,但是这里的问题是当我告诉代码从此处告诉此范围并在此处粘贴时,我不知道粘贴功能的范围,我不能告诉他复制所有数据并从该范围开始粘贴以告知数据完成吗?

另一个问题是,当我复制所有数据时,我拥有的所有图形都消失了吗?

是python的新手,请保持柔和:)

import openpyxl

#Prepare the spreadsheets to copy from and paste too.

#File to be copied
wb = openpyxl.load_workbook(r"C:\Users\Toshiba\Desktop\New Test\row.xlsx") #Add file name
sheet = wb.get_sheet_by_name("Sheet1") #Add Sheet name

#File to be pasted into
template = openpyxl.load_workbook(r"C:\Users\Toshiba\Desktop\New Test\Template.xlsx") #Add file name
temp_sheet = template.get_sheet_by_name("1") #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,12,1054,sheet) #Change the 4 number values
    pastingRange = pasteRange(1,2110,12,0,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("saeed.xlsx")
    print("Range copied and pasted!")

0 个答案:

没有答案