padas生成excel増加sheetテーブル

3786 ワード

基本的な紹介
pandasはPythonデータマイニング、データ分析でよく使われるライブラリです.一方、DataFrameはexcelのsheetテーブルを生成し、excelにsheetテーブルを追加し、データ分割
析中にもよく使われる.ここでは、この2つの機能の使い方を簡単な例で紹介し、必要に応じて説明します.
例:

#!/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)