1. 程式人生 > 其它 >【Python】Pandas 操作Excel

【Python】Pandas 操作Excel

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Time    :2022/3/27 16:14
@Author  :
@File    :PandasUtil.py
@Version :1.0
@Function:
"""

import pandas as pd


class PandasUtil:
    @staticmethod
    def readExcel(excelFile: str):
        """
        Pandas讀取Excel資料
        :param excelFile:
        :return:
        
""" # header=None:表示所有資料均為body資料(沒有表頭) 反之不傳header 則有表頭(讀到的資料是沒有表頭的) # data = pd.read_excel(excelFile, header=None) data = pd.read_excel(excelFile) # data.values 是pandas讀取到的資料(二維陣列) data.values[0][0]:表示第0行第0列 print(data.values[0][3]) # 列印第0行第3列的單元格資料 @staticmethod
def writeNewExcel(newExcelFile: str): """ Pandas新建Excel檔案(若已有檔案 則直接覆蓋原檔案) :param newExcelFile: :return: """ # 表頭資料 cols = ['序號', '名稱', '備註1'] # 表體資料 data = [ ['1', '哈哈', '哈哈備註'], ['2', '看看', '看看備註'] ] df
= pd.DataFrame(columns=cols, data=data) df.to_excel(newExcelFile, index=False) # 一般需要傳index=False @staticmethod def writeAppendExcel(excelFile: str): """ Pandas往已有的Excel表中追加資料 :param excelFile: :return: """ # 1 把Excel中已有的資料讀取到DataFrame中 dfOld = pd.read_excel(excelFile, header=None) # 建議傳header=None appendData = [ ['5', '姓名追加', '100', '不男不女', '姓名追加的備註'] ] # 2 把待追加的資料轉換為DataFrame資料 dfAppend = pd.DataFrame(appendData) # 3 新老資料合併成一個新的DataFrame資料 dfNew = dfOld.append(dfAppend, ignore_index=True) # 一般需要傳ignore_index=True # 4 把新的DataFrame資料寫入Excel中 dfNew.to_excel(excelFile, index=False, header=False) # 建議傳header=False (須於第一步一致) if __name__ == '__main__': # Pandas讀取Excel資料 # excelFile = r"E:\pandas\pandasTest.xlsx" # PandasUtil.readExcel(excelFile) # Pandas新建Excel檔案 # excelFile = r"E:\pandas\newPandasTest.xlsx" # PandasUtil.writeNewExcel(excelFile) # Pandas往已有的Excel表中追加資料 excelFile = r"E:\pandas\pandasTest.xlsx" PandasUtil.writeAppendExcel(excelFile)