我正在尝试使用 xlwings 自动创建数据透视表。这是我创建的一段随机代码,它应该创建一个数据透视表,但我在创建数据透视表的行处收到错误。我无法越过这一行,我的调试器立即退出。
知道发生了什么事吗?
import xlwings as xw
from xlwings import constants
def get_pivot():
# Create a sample DataFrame
df = pd.DataFrame({
'Date': pd.date_range(start='2023-01-01', periods=100),
'Product': np.random.choice(['A', 'B', 'C'], 100),
'Region': np.random.choice(['North', 'South', 'East', 'West'], 100),
'Sales': np.random.randint(100, 1000, 100)
})
# Start an Excel application
wb = xw.Book(path_to_excel)
ws = wb.sheets["Sheet1"]
# Clear the contents of the worksheet
ws.clear_contents()
# Write the DataFrame to Excel
ws.range('A1').options(index=False).value = df
# Get the data range
data_range = ws.range('A1').expand()
# Create PivotCache
pivot_cache = wb.api.PivotCaches().Create(SourceType=constants.PivotTableSourceType.xlDatabase, SourceData=data_range.api) # , Version=constants.PivotTableVersionList.xlPivotTableVersion14)
pivot_table = pivot_cache.CreatePivotTable(TableDestination=ws.range('F2'), TableName='SalesPivot')
# Configure pivot table fields
pivot_table = ws.api.PivotTables("SalesPivot")
# Configure the pivot table fields
pivot_table.PivotFields('Date').Orientation = xw.constants.PivotFieldOrientation.xlRowField
pivot_table.PivotFields('Date').NumberFormat = "yyyy-mm-dd"
pivot_table.PivotFields('Product').Orientation = xw.constants.PivotFieldOrientation.xlColumnField
pivot_table.PivotFields('Region').Orientation = xw.constants.PivotFieldOrientation.xlPageField
pivot_table.PivotFields('Sales').Orientation = xw.constants.PivotFieldOrientation.xlDataField
# Set Data Field
sales_field = pivot_table.PivotFields('Sales')
sales_field.Orientation = xw.constants.PivotFieldOrientation.xlDataField
sales_field.Function = xw.constants.ConsolidationFunction.xlSum
# Save the workbook
print("Pivot table created successfully!")
if __name__ == '__main__':
xw.serve()
我使用 xlwings 调试器进行调试,每次处理行数据透视表时,代码总是退出调试器。
我修改了添加的行
Version=constants.PivotTableVersionList.xlPivotTableVersion14
但它也不起作用:
pivot_cache = wb.api.PivotCaches().Create(SourceType=constants.PivotTableSourceType.xlDatabase, SourceData=data_range.api, Version=constants.PivotTableVersionList.xlPivotTableVersion14)
我认为您只是对表格位置值有疑问。
以下示例合并了您的数据框和代码,以在一个命令中创建数据透视表,而不是使用两个命令,但如果您希望单独执行这些步骤,您可以这样做。
该代码使用上下文管理器,它将在保存 Excel 工作簿后包装 Excel 实例。
如果您有要求,可以将其放置在函数中。
import xlwings as xw
from xlwings import constants
import pandas as pd
import numpy as np
path_to_excel = 'foo.xlsx'
with xw.App(visible=True) as xl:
# Create a sample DataFrame
df = pd.DataFrame({
'Date': pd.date_range(start='2023-01-01', periods=100),
'Product': np.random.choice(['A', 'B', 'C'], 100),
'Region': np.random.choice(['North', 'South', 'East', 'West'], 100),
'Sales': np.random.randint(100, 1000, 100)
})
# Start an Excel application
wb = xl.books.open(path_to_excel)
ws = wb.sheets["Sheet1"]
# Clear the contents of the worksheet
ws.clear_contents()
# Write the DataFrame to Excel
ws.range('A1').options(index=False).value = df
# Get the data range
data_range = ws.range('A1').expand()
# Set the Pivot Table Name
table_name = "SalesPivot"
# Set the Pivot Table Destination
table_location = ws.range('F2')
# Create Pivot Table
pivot_table = wb.api.PivotCaches().Create(
SourceType=constants.PivotTableSourceType.xlDatabase,
SourceData=data_range.api).CreatePivotTable(
TableDestination=table_location.api,
TableName=table_name)
# Configure the pivot table fields
pivot_table.PivotFields('Date').Orientation = xw.constants.PivotFieldOrientation.xlRowField
pivot_table.PivotFields('Date').NumberFormat = "yyyy-mm-dd"
pivot_table.PivotFields('Product').Orientation = xw.constants.PivotFieldOrientation.xlColumnField
pivot_table.PivotFields('Region').Orientation = xw.constants.PivotFieldOrientation.xlPageField
pivot_table.PivotFields('Sales').Orientation = xw.constants.PivotFieldOrientation.xlDataField
# Set Data Field
sales_field = pivot_table.PivotFields('Sales')
sales_field.Orientation = xw.constants.PivotFieldOrientation.xlDataField
sales_field.Function = xw.constants.ConsolidationFunction.xlSum
# Save the workbook
wb.save('PivotTable.xlsx')
print("Pivot table created successfully!")