excel的数据透视表可以帮助我们快速统计数据,排版。比自己开发脚本,要快捷很多。对指定的区域的数据创建透视表
import win32com.client as win32
from win32com.client import constants
xls_app = win32.gencache.EnsureDispatch('Excel.Application')
wb = xls_app.Workbooks.Add()
ws = wb.Worksheets(1)
ws.Name = 'my_new_sheet'
xls_app.Visible = True
wb.SaveAs('New_workbook.xlsx')
#写入数据
ws.Range("A1").Value = "省份"
ws.Range("A2").Value = "四川"
ws.Range("A3").Value = "广西"
ws.Range("B1").Value = "省会"
ws.Range("B2").Value = "成都"
ws.Range("B3").Value = "南宁"
#添加透视表的数据源
SrcData = ws.Range("A1:B3")
#添加一个新的sheet,用于存放生成的透视表
pt_sht = wb.Worksheets.Add()
pt_sht.Name = "透视表"
StartPvt = pt_sht.Range("A1")
#
pt_cache = wb.PivotCaches().Create(SourceType=constants.xlDatabase, SourceData=SrcData)
pt = pt_cache.CreatePivotTable(TableDestination=StartPvt, TableName="PivotTable1")
2读取透视表的内容(待补充)