以下代码在PivotCache.CreatePivotTable()语句之前不出错地执行。Excel或windows在某些方面有问题。错误消息表明问题在于传递的参数,但这似乎不是正确的错误消息。
我可以在VBA中执行相同的方法,并且在没有错误的情况下工作(语法略有不同,但传递相同的参数值)。
我需要以不同的方式输入参数吗?
代码
Excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
win32c = win32com.client.constants
####\#load the workbook
wb = Excel.Workbooks.Open('c:\devworkspace\SQL-Pandas-Excel\LargeClaims.xlsx')
####\#create a worksheet object for source data
src_sheet = wb.Worksheets('Total Direct Pay')
####\#add the pivot table work sheet and name
pvt_sheet = wb.Sheets.Add(After=src_sheet)
pvt_sheet.Name = 'Pivot Sheet'
####\#set the source range "Total Direct Pay!R2C2:R162855C19"
rng_row = int(largest_claims_df.shape[0])
rng_col = int(largest_claims_df.shape[1])
pvt_src = "%s!R2C2:R%dC%d"%(src_sheet.Name,rng_row+1,rng_col+1) \# offset index and header
####\#Create the Pivot Cache
pc = wb.PivotCaches().Add(SourceType=win32c.xlDatabase, SourceData=pvt_src)
####\#Create the Pivot Table
try:
pt = pc.CreatePivotTable(TableDestination='Pivot Sheet!R4C1',TableName='PivotTable1')
except pythoncom.com_error as error:
print(error.excepinfo[5])
print(win32api.FormatMessage(error.excepinfo[5]))以下是错误代码和已翻译的消息:
-2147024809
The parameter is incorrect.此外,未处理完整的堆栈跟踪:
---------------------------------------------------------------------------
com_error Traceback (most recent call last)
<ipython-input-16-6924c75f990d> in <module>()
7
8
----> 9 pt = pc.CreatePivotTable(TableDestination='Pivot
Sheet!R4C1',TableName='PivotTable1')
10
11
C:\Users\BARTRA~1\AppData\Local\Temp\gen_py\3.6\00020813-0000-0000-C000- 000000000046x0x1x8\PivotCache.py in CreatePivotTable(self, TableDestination, TableName, ReadData, DefaultVersion)
43 def CreatePivotTable(self, TableDestination=defaultNamedNotOptArg, TableName=defaultNamedOptArg, ReadData=defaultNamedOptArg, DefaultVersion=defaultNamedOptArg):
44 ret = self._oleobj_.InvokeTypes(1836, LCID, 1, (9, 0), ((12, 1), (12, 17), (12, 17), (12, 17)),TableDestination
---> 45 , TableName, ReadData, DefaultVersion)
46 if ret is not None:
47 ret = Dispatch(ret, 'CreatePivotTable', '{00020872-0000-0000-C000-000000000046}')
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None)发布于 2018-08-09 17:04:54
下面描述的解决方案对我是有效的。我发现的所有示例都传递一个具有这种格式的字符串:“Pivot!R4C1”。我也尝试了‘数据透视表!R4C1:R4C1’,但是得到了同样的错误。
对于PivotCache.CreatePivotTable:"TableDestination“参数需要是Range对象:
pvt_rng_beg = pvt_sheet.Cells(2,2)
pvt_rng_end = pvt_sheet.Cells(2,2)
pvt_dest_rng = pvt_sheet.Range(pvt_rng_beg, pvt_rng_end)
pt = pc.CreatePivotTable(TableDestination=pvt_dest_rng,TableName='PivotTable1')摘自C#文档:
TableDestination对象所需对象。PivotTable报表目标区域左上角的单元格(将放置结果PivotTable报表的工作表上的区域)。目标范围必须位于包含表达式指定的PivotCache对象的工作簿中的工作表上。
这是PivotCache.CreatePivotTable(对象,对象)方法在C#中的文档。但是,它仍然没有指定参数对象的所需类型。我是经过反复试验才达到这一目标的。
还找到了相同对象和方法PivotCache.CreatePivotTable方法(Excel)的MSDN文档。
https://stackoverflow.com/questions/51732854
复制相似问题