如何在不影响列名和python保持相同格式的情况下,将数据从特定的Excel工作表复制到其他位置的另一个Excel工作表。
import xlwings as xw
P1 = 'C:\\Users\\User\\Desktop\\W1.xlsx'
P2 = 'C:\\Users\\User\\Desktop\\W2.xlsx'
wb1 = xw.Book(P1)
wb2 = xw.Book(P2)
ws1 = wb1.sheets(1)
ws1.api.Copy(Before=wb2.sheets(1).api)
wb2.save()
wb2.app.quit()
此代码实际上是在excel中创建一个新工作表,但是我希望它在不更改工作表头的情况下转移到特定工作表中。
答案 0 :(得分:0)
import openpyxl as xl
path1 = 'C:\\Users\\Xukrao\\Desktop\\workbook1.xlsx'
path2 = 'C:\\Users\\Xukrao\\Desktop\\workbook2.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)