[英]How to copy and paste data from each excel sheet into a final sheet using Python?
[英]Python/Pandas copy and paste from excel sheet
我發現此語法可以將一個工作簿特定的工作表復制並粘貼到另一工作簿中。 但是,我需要幫助的是如何將復制的信息粘貼到第二個工作簿/工作表中的特定單元格。 就像我需要將信息粘貼到單元格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”
由於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”的樣子:
這是“ new.xlsx”的樣子:
感謝您對我的幫助。 我找到了稍作修改的答案。 我刪除了最后一個def語句,並保留了其他所有內容。 它的工作原理非常好。 復制並粘貼到我需要的位置,而無需從模板中刪除任何內容。
`#! Python 3
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.