padas 生成excel 增加sheet表

基本介绍

  pandas是Python数据挖掘、数据分析中常用的库。而DataFrame生成excel中的sheet表,以及在excel中增加sheet表,在数据分

析中也经常用到。这里以一个简单例子介绍这两个功能的用法,以备不时之需。


例子:


#!/usr/bin/env python


# -*- coding: utf-8 -*-

"""
Version: 0.1
Author: Wang Pei
License: Copyright(c) 2017 Pei.Wang
Summary:
   (1)padas dataframe生成excel
   (2)excel中增加sheet表
"""
import sys
import pandas as pd
from openpyxl import load_workbook

reload(sys)
sys.setdefaultencoding('utf-8')


"""
padas dataframe生成excel
"""
def dataFrame2sheet(dataframe,excelWriter):

   # DataFrame转换成excel中的sheet表
   dataframe.to_excel(excel_writer=excelWriter, sheet_name="info1",index=None)
   dataframe.to_excel(excel_writer=excelWriter, sheet_name="info2",index=None)
   dataframe.to_excel(excel_writer=excelWriter, sheet_name="info3",index=None)

   excelWriter.save()
   excelWriter.close()

"""
excel中新增sheet表
"""
def excelAddSheet(dataframe,excelWriter):

   book = load_workbook(excelWriter.path)
   excelWriter.book = book
   dataframe.to_excel(excel_writer=excelWriter,sheet_name="info5",index=None)
   excelWriter.close()

if __name__ == '__main__':

   # 数据集
   dataSet = [
       {"姓名": "张三", "年龄": 23, "性别": "男"},
       {"姓名": "李四", "年龄": 25, "性别": "男"},
       {"姓名": "王五", "年龄": 21, "性别": "女"}
   ]

   # excelPath
   excelPath="G:\cmcm\ReportAuto\\02TestData\\x.xlsx"

   # 生成DataFrame
   dataframe = pd.DataFrame(dataSet)


   #创建ExcelWriter 对象
   excelWriter=pd.ExcelWriter(excelPath,engine='openpyxl')

   # #生成excel
   #dataFrame2sheet(dataframe,excelWriter)

   #excel中增加sheet
   excelAddSheet(dataframe,excelWriter)

你可能感兴趣的:(Python)