win32com Excel 粘贴特殊格式
我在用Python的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'
我知道“paste”是一个关键字参数,因为在MSDN上有说明,链接在这里:
http://msdn.microsoft.com/en-us/library/office/ff839476(v=office.15).aspx你知道为什么我不能这样做吗?在网上找了很多资料,但没找到什么有用的信息。
编辑以提供解决方案:
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)
2 个回答
3
你可以通过在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)
2
我不太用Python,不过在Excel的VBA里,如果你想用PasteSpecial
功能,就得指定你想粘贴到哪个单元格。所以你可以试试这样写:
Sheet1.Range("C1").PasteSpecial(Paste=constants.xlPasteValues)
如果你只是想简单地粘贴,那我觉得这样应该可以用:
Sheet1.Paste