我尝试打开一个名为'N11 Result.xlsx'的现有工作簿。复制整个工作表'Sheet1'(首先将其重命名为'使用Python')...并粘贴到同一工作簿中的新工作表(名为'Annual')。我认为我的代码的最后一行不起作用......任何帮助都会有所帮助。
import os,sys
sys.path.append(r"""U:\Programming\Python\Python Manipulate Excel""")
work_dir=r"""U:\Programming\Python\Python Manipulate Excel"""
file_name='N11 Result.xlsx'
import win32com.client
excel = win32com.client.Dispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Open(work_dir+'\\'+file_name)
ws = wb.Worksheets('Sheet1')
ws.Name = 'Built with Python'
wb.Worksheets("Built with Python").Copy(before=wb.Worksheets("Annual"))
excel.Application.Quit()
出现的错误消息将是
Traceback(最近一次调用最后一次): 文件“U:\ Programming \ Python \ Python Manipulate Excel \ Test_createExcel_01.py”,第17行,in wb.Worksheets(“用Python构建”)。复制(在= wb.Worksheets(“Annual”)之前) 文件“C:\ Temp \ gen_py \ 2.7 \ 00020813-0000-0000-C000-000000000046x0x1x7 \ Sheets.py”,第113行,致电 ret = self._oleobj_.InvokeTypes(0,LCID,2,(9,0),((12,1),),索引 com_error:( - 214703567,'发生异常。',(0,无,无,无,0,-2147352565),无)
答案 0 :(得分:2)
因此,您可以使用pywin32将整个工作表复制到新工作表中:
# old_sheet: sheet that you want to copy
old_sheet.Copy(pythoncom.Empty, workbook.Sheets(workbook.Sheets.Count)
new_sheet = workbook.Sheets(workbook.Sheets.Count)
new_sheet.Name = 'Annual'
答案 1 :(得分:2)
import win32com.client as win32
from copy import copy
excel = win32.gencache.EnsureDispatch('Excel.Application')
#excel.Visible = False
excel.DisplayAlerts = False
wb0 = excel.Workbooks.Open(dirname + '\\' + 'original.xlsx')
ws0 = wb0.Worksheets('Original_sheet')
wb2 = excel.Workbooks.Open(dirname + '\\' + writer.path)
ws2 = wb2.Worksheets.Add()
ws2.Name = 'Copy_original'
ws2 = wb2.Worksheets('Copy_original')
ws0.Range("A1:AF100").Copy(ws2.Range("A%s:AF%s" % (row, col)))
wb2.Save()
excel.Application.Quit()
答案 2 :(得分:0)
尝试使用以下代码切换wb.Worksheets("Built with Python").Copy(before=wb.Worksheets("Annual"))
。
wb.Worksheets("Built with Python").Cells.Select()
excel.Selection.Copy(Destination=wb.Worksheets("Annual").Range("A1"))
如果有效,请告诉我。如果它不起作用,它可能是您尝试构建的目录可能是原因。