win32com Excel PasteSpecial

问题描述:

我在使用PasteSpecial时遇到了一些麻烦。这里的示例代码:win32com Excel PasteSpecial

import win32com.client as win32com 
from win32com.client import constants 

xl = win32com.gencache.EnsureDispatch('Excel.Application') 
xl.Visible = True 
wb = xl.Workbooks.Add() 
Sheet1 = wb.Sheets("Sheet1") 

# Fill in some summy formulas 
for i in range(10): 
    Sheet1.Cells(i+1,1).Value = "=10*"+str(i+1) 

Sheet1.Range("A1:A16").Copy() 
Sheet1.Range("C1").Select() 
Sheet1.PasteSpecial(Paste=constants.xlPasteValues) 

,我发现了以下错误:

TypeError: Paste() got an unexpected keyword argument 'Paste' 

我知道糊是因为这里的MSDN的关键字参数: http://msdn.microsoft.com/en-us/library/office/ff839476(v=office.15).aspx

知道为什么它不会让我这样做?在网络上无法真正找到。

编辑为溶液(S):

import win32com.client as win32com 
from win32com.client import constants 

xl = win32com.gencache.EnsureDispatch('Excel.Application') 
xl.Visible = True 
wb = xl.Workbooks.Add() 
Sheet1 = wb.Sheets("Sheet1") 

# Fill in some summy formulas 
for i in range(10): 
    Sheet1.Cells(i+1,1).Value = "=10*"+str(i+1) 

Sheet1.Range("A1:A16").Copy() 
Sheet1.Range("C1").PasteSpecial(Paste=constants.xlPasteValues) 
# OR this I just found right after I posted this works as well: 
xl.Selection.PasteSpecial(Paste=constants.xlPasteValues) 
+3

我不工作python,但试试这个'Sheet1.Range(“C1”)。PasteSpecial(Paste = constants.xlPasteValues)' – 2014-10-30 23:42:08

+0

这工作。做出回答,并接受它。 – 2014-10-30 23:45:14

+0

关于你的编辑:你应该避免使用'.Select/Selection'。您可能想查看[THIS](http://*.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros/10718179#10718179)Excel-VBA链接 – 2014-10-30 23:48:53

我不蟒蛇工作,但在Excel的VBA做PasteSpecial,就不得不提到要执行PasteSpecial的细胞,所以尝试像

Sheet1.Range("C1").PasteSpecial(Paste=constants.xlPasteValues) 

如果你想要一个简单的粘贴那么我想这应该工作

Sheet1.Paste 

你可以在Excel VB执行宏xlPasteFormats值:

Sub Macro2() 
    Range("A7").Select 
    ActiveCell.FormulaR1C1 = xlPasteFormats 
End Sub 

为xlPasteFormats值为-4122

在Python脚本可以使用

xlSheet.Range("A7:H7").Copy() 
xlSheet.Range("A%s:H%s"%(r,r)).PasteSpecial(Paste=-4122)