nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

pandasのread_excelでExcelファイルのリード・ライト

pandasのread_excelExcelファイルのリード・ライトを簡単に実施したい

pythonExcelを扱うにはいくつかの方法がありますが、pandasのread_excelをここでは取り上げます。

上記を簡単に扱えるように、ラッパークラスを作成してみました。

import pandas as pd

class ExcelAccess():

    def __init__(self, file_path, header_row = None):
        """
        引数:
            file_path : string : 開くExcelファイルのフルパスを入力
            header_row : int : ヘッダー行を指定(0行) (ヘッダー行がない場合はNone)
        """
        # Excelファイル名
        self.file_path = file_path

        # ヘッダー行の有無
        self.headerExits = (header_row != None)
        
        # ヘッダー行 (ヘッダー行が存在しない場合は-1)
        self.headerLineCount = header_row if self.headerExits else -1

        self.df = self.ReadExcel()
    
    def ReadExcel(self):

        if not self.headerExits:
            return pd.read_excel(self.file_path, dtype=str, encoding='utf8', header=None)
        
        return pd.read_excel(self.file_path, dtype=str, encoding='utf8', header=self.headerLineCount)
        

    def ReadCell(self, row_index, column_index):
        """セルの値を取得する
        引数 : 
            row_index : int : データ行 (最初のデータであれば0)
            column_index : int : データ列(最初のデータであれば0)
        戻り値 : str
        """
        return self.df.iloc[row_index, column_index]


    def ReadRow(self, row_index):
        """行のデータを取得する
        引数 : 
            column_index : int : データ列(最初のデータであれば0)
        戻り値 : str型の一次元配列 : <class 'numpy.ndarray'>
        """
        return self.df.iloc[row_index, 0:].values


    def ReadColumn(self, column_index):
        """列のデータを取得する
        引数 : 
            row_index : int : データ行 (最初のデータであれば0)
        戻り値 : 一次元配列 : <class 'numpy.ndarray'>
        """
        return self.df.iloc[0:, column_index].values


    def ReadArea(self, start_cell, end_cell):
        """範囲を取得する
        引数 : 
            start_cell : tuple(int,int) : 開始地点のセルのタプル(行番号 : 列番号)
            end_cell : tuple(int,int) :  終了地点のセルのタプル(行番号 : 列番号)
        戻り値 : 二次元配列 : <class 'numpy.ndarray'>
        """
        
        start_row, start_column = start_cell
        end_row, end_column = end_cell
        
        return self.df.iloc[start_row:end_row, start_column:end_column].values

    def ReadAll(self):
        """全範囲を取得する
        引数 : 
        戻り値 : 二次元配列 : <class 'numpy.ndarray'>
        """
        return self.df.values

    def WriteCell(self, row_index, column_index, value):
        """セルに値を設定する
        引数 : 
            row_index : int : データ行 (最初のデータであれば0)
            column_index : int : データ列(最初のデータであれば0)
            param : str : 書き込む値
        戻り値 : str
        """
        self.df.iloc[row_index, column_index] = value


    def SaveExcel(self):
        # ヘッダーがあれば、ヘッダーを付与。ヘッダー行数が2行目の場合は、1行目を空白行とする
        self.df.to_excel(self.file_path, index=False, header=self.headerExits, startrow = self.headerLineCount)

import chrome_driver
import excel_access

# Excelファイルを文字列として読み込む
excel = excel_access.ExcelAccess("database.xlsx", 2)

# 全データを取得する 
print(excel.ReadAll())

# セルの値を取得
print(excel.ReadCell(1,1))

# 行の値を取得
for item in excel.ReadRow(0):
    print(item)

# 列の値を取得
for item in excel.ReadColumn(0):
    print(item)

# 範囲の値を取得
for item in excel.ReadArea((0,0),(2,2)):
    print(item)

# 全データを取得する 
print(excel.ReadAll())

# セルに値を設定する
excel.WriteCell(0, 3,"Password21")

# 全データを取得する 
print(excel.ReadAll())

# Excelに保存する
excel.SaveExcel()

参考

  • 特定列のみ型指定して取得する
  • Python)pandas read_excelExcelの特定列のみ型指定して取得する
  • https://qiita.com/ttn_tt/items/ed8b184a97e78c441fae

  • 読み込む列と読み込まない列を指定する

  • 1, 3, 5列目を読み込み、且つ6, 7行目は読み込まない
  • pd.read_excel('test.xlsx', header=None, index_col=None, usecols=[1, 3, 5], skiprows=[5, 7])