Python Module_openpyxl_Excelテーブルの操作


目次
  • ディレクトリ
  • 前言
  • ソフトウェアシステム
  • Install openpyxl module
  • Sample code
  • load_workbook Excelファイルのロード
  • wbObjectget_sheet_names取得Excelテーブル名
  • WorkbooktableName位置決めExcelテーブル
  • WbObjectget_sheet_by_namesheetName位置決めExcelテーブル
  • WorksheetrowsとWorksheetcolumnsテーブルの行列値を取得
  • Worksheetを取得する行列数
  • スライス演算子により表領域
  • を分割する.
  • get_column_letterは、1つのカラムのインデックスをカラムのアルファベット
  • に変換する
  • Worksheetcellvalueセルのデータ値の配置
  • 直接セルに
  • を割り当てます.
  • Woeksheetget_cell_collectionはすべてのセルデータ値
  • を取得する
  • enumerateiterators反復器のインデックスと要素
  • を取得
  • Workbooksaveすべての操作を保存し、新しいExcelファイル
  • を生成します.
  • Workbook新しいExcelファイルを作成
  • wbObjectcreate_Sheet Excelテーブル
  • を作成
  • Worksheetappend行ごとにセル
  • に数値を追加
  • ExcelWriter WorkbookオブジェクトをExcelファイル
  • に書き込む
  • 最後の
  • 前言
    PythonがExcelテーブルを処理するには、いくつかの方法がある.xlsx接尾辞のExcelバージョンではopenpyxlは絶対に素晴らしい選択です.Openpyxlでは、ExcelファイルがWorkbookであり、ExcelファイルのテーブルがWorksheetです.Excelファイルを処理する必要がある場合は、まずワークブックオブジェクトを取得し、ワークシートオブジェクトを取得し、ワークシートオブジェクトのrows、columnsをデータ処理し、最後にワークブックを通過する必要があります.save()メソッドは、Workbookオブジェクトの内容をディスクに書き込みます.あるいはOpenpyxlに組み込まれたExcelWriter()メソッドを使用してWorkbookオブジェクトを関連付け、最終的に書き込みを実現することもできます.
    ソフトウェアシステム
  • システム
  • Windows 8.1

  • ソフトウェア
  • Python 3.4.3


  • Install openpyxl module
    Python 3を使う.4.3付属のパッケージ管理ツールeasy_install.exeはopenpyxlモジュールRun(Ctrl+r)cmdをインストールする
    cd %pythonRoot%\Scripts
    easy_install.exe openpyxl

    Check:インストール後にopenpyxlモジュールをインポートしてもImportErrorはトリガーされません
    import openpyxl

    Sample code
    from openpyxl import Workbook
    wb = Workbook()
    
    # grab the active worksheet
    ws = wb.active
    
    # Data can be assigned directly to cells
    ws['A1'] = 42
    
    # Rows can also be appended
    ws.append([1, 2, 3])
    
    # Python types will automatically be converted
    import datetime
    ws['A2'] = datetime.datetime.now()
    
    # Save the file
    wb.save("sample.xlsx")

    Documentation:http://openpyxl.readthedocs.org
    load_workbook()Excelファイルのロード
    Excelファイルをworkbookと呼び、workbookには多くのworksheet(ワークシート)が含まれています.ワークブック['sheetName']でワークシートを特定できます.メモリへのファイルのインポート
    load_workbook(filename, read_only=False, use_iterators=False, keep_vba=False, guess_types=False, data_only=False)
    In [7]: help(load_workbook)
    Help on function load_workbook in module openpyxl.reader.excel:
    
    load_workbook(filename, read_only=False, use_iterators=False, keep_vba=False, guess_types=False, data_only=False)
        Open the given filename and return the workbook
    
        :param filename: the path to open or a file-like object
        :type filename: string or a file-like object open in binary mode c.f., :class:`zipfile.ZipFile`
    
        :param read_only: optimised for reading, content cannot be edited
        :type read_only: bool 
    
        :param use_iterators: use lazy load for cells
        :type use_iterators: bool
    
        :param keep_vba: preseve vba content (this does NOT mean you can use it)
        :type keep_vba: bool
    
        :param guess_types: guess cell content type and do not read it from the file
        :type guess_types: bool
    
        :param data_only: controls whether cells with formulae have either the formula (default) or the value stored the last time Excel read the sheet
        :type data_only: bool
    
        :rtype: :class:`openpyxl.workbook.Workbook`

    Filename(str or file-like object):Excelファイルのパスまたはクラスファイルオブジェクトです.read_only(bool):読み取り専用モードで、ファイルを編集できません.デフォルトはFalse use_iterators(bool):遅延ロードを呼び出すかどうか.デフォルトはFalse keep_vba(bool):VBAの内容を保持するかどうか.デフォルトはFalse guess_type(bool):セルの内容のタイプを取得し、ファイルから読み込めません.デフォルトはFalse date_only(bool):数式を含むセルに数式があるかどうかを制御するか、または最後にExcelテーブルを読み込むリードタイムを記憶するNote:When using lazy load,all worksheets will be class:{openpyxl.worksheet.iter_worksheet.IterableWorksheet}and the returned workbook will be read-only.
    In [29]: from openpyxl import load_workbook
    
    In [5]: getwb = load_workbook(filename=r"Handoff.xlsx")   #    Workbook  
    
    In [6]: getwb
    Out[6]: 0x4b7c030>

    getwbはWorkbookオブジェクトであり、Workbook()は最も基本的なクラスであり、メモリにファイルを作成して最後にファイル内容をディスクに書き込むことができます.
    wbObject.get_sheet_names()Excelテーブル名の取得
    In [70]: getwb.get_sheet_names()    #    Excel       
    Out[70]: ['NodeCount']
    
    In [75]: getwb.get_sheet_names()[0]
    Out[75]: 'NodeCount'

    Workbook[tableName]位置決めExcelテーブル
    Openpyxlモジュールは、辞書キー値対マッピングのような方法でテーブルの内容を取得することをサポートします.
    In [80]: sheetContent = getwb[getwb.get_sheet_names()[0]]
    
    In [84]: type(sheetContent)
    Out[84]: openpyxl.worksheet.worksheet.Worksheet      #    Worksheet  ,        

    WbObject.get_sheet_by_名前(sheetName)Excelテーブルの配置
    In [57]: sheet1 = getwb.get_sheet_by_name('NodeCount')

    Worksheet.rowsとWorksheet.columnsテーブルの行列値の取得
    In [89]: sheetContent.rows
    Out[89]:
    ((.A1>,
      .B1>,
      .C1>,
      .D1>),
     (.A2>,
      .B2>,
      .
      .
      .
    In [90]: len(sheetContent.rows)
    Out[90]: 25
    
    In [93]: len(sheetContent.columns)
    Out[93]: 4

    Worksheetの取得行列数
    In [115]: sheetContent.get_highest_row()
    
    In [117]: sheetContent.get_highest_column()

    表領域をスライス演算子で区切る
    なぜならrowsとWorksheet.columnsはいずれもTupleデータ型であり,スライス演算子の使用をサポートする.
    In [100]: type(sheetContent.rows),type(sheetContent.columns)
    Out[100]: (tuple, tuple)

    1.sheetContentの最初の2列の内容を取得する
    In [103]: colA,colB = sheetContent.columns[:2]

    2.2 D領域の分割
    In [112]: cells = sheetContent['A1':'C3']    #         
    
    In [113]: type(cells)
    Out[113]: generator

    get_column_letterは、1つのカラムのインデックスをカラムのアルファベットに変換します.
    get_column_letter(idx) Convert a column index into a column letter (3 -> ‘C’)
    In [122]: from openpyxl.cell import get_column_letter
    
    In [124]: for x in list(range(1,11)):
       .....:     ch = get_column_letter(x)
       .....:     print(ch)
       .....:
    A
    B
    C
    D
    E
    F
    G
    H
    I
    J

    Worksheet.cell().value位置決めセルのデータ値
    指定された座標(A 1)に基づいてセルオブジェクトを返します.cell(coordinate=None, row=None, column=None, value=None) method of openpyxl.worksheet.worksheet.Worksh Returns a cell object based on the given coordinates.
    Usage: cell(coodinate='A15') **or** cell(row=15, column=1)
    
    If `coordinates` are not given, then row *and* column must be given.
    
    Cells are kept in a dictionary which is empty at the worksheet
    creation.  Calling `cell` creates the cell in memory when they
    are first accessed, to reduce memory usage.
    
    :param coordinate: coordinates of the cell (e.g. 'B12')
    :type coordinate: string
    
    :param row: row index of the cell (e.g. 4)
    :type row: int
    
    :param column: column index of the cell (e.g. 3)
    :type column: int
    
    :raise: InsufficientCoordinatesException when coordinate or (row and column) are not given
    
    :rtype: :class:openpyxl.cell.Cell
    
    In [117]: sheetContent.cell("A1")
    Out[117]: <Cell NodeCount.A1>
    
    In [118]: sheetContent.cell("A1").value
    Out[118]: 'Cluster'
    
    In [120]: sheetContent.cell(row=1,column=2).value
    Out[120]: 'HI'

    注意:Excelテーブルのデータには、両側にスペース記号が付随することが多いので、Str.strip()を使用して余分なスペース記号を除去する必要があります.
    セルに直接値を割り当てる
    A列をすべてNoneにする
    In [127]: colALen = len(sheetContent.columns[0])
    
    In [128]: for i in list(range(1,colALen+1)):
       .....:     sheetContent.cell('A%s' % i).value = None
       .....:

    注意:セルに値を割り当てる場合、Excelのデータ型は値を割り当てるデータ型によって決まります.
    Woeksheet.get_cell_collection()すべてのセルデータ値を取得
    すべてのcellの数値を取得しますが、順序はありません.get_cell_collection() method of openpyxl.worksheet.worksheet.Worksheet instance Return an unordered list of the cells in this worksheet. すべてのセルを含む無秩序なリストを返します.
    In [59]: sheetContent.get_cell_collection()

    Enumerate(iterators)反復器のインデックスと要素の取得
    enumerate(iterable[, start]) -> iterator for index, value of iterable Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. Enumerate is useful for obtaining an indexed list:(0,seq[0]),(1,seq[1]),(2,seq[2]),...反復器タイプの実パラメータを受信し、(インデックス,要素)を含む反復器を返します.
    In [46]: row1,row2 = sheetContent.rows[:2]
    
    In [49]: for index,cell in enumerate(row1):
       ....:     print(index,cell)
       ....:
    0 .A1>
    1 .B1>
    2 .C1>
    3 .D1>

    Workbook.save()すべての操作を保存し、新しいExcelファイルを生成
    指定したファイル名はこのExcelファイルを保存します.save(filename) method of openpyxl.workbook.workbook.Workbook instance Save the current workbook under the given filename. Use this function instead of using an ExcelWriter.
    .. warning::
        When creating your workbook using `write_only` set to True,
        you will only be able to call this function once. Subsequents attempts to
        modify or save the file will raise an :class:`openpyxl.shared.exc.WorkbookAlreadySaved` exception.
    
    In [134]: getwb.save('test.xlsx')

    Workbook()新しいExcelファイルを作成する
    新しいWorkbookオブジェクトclass Workbook(builtins.object)Workbook is the container for all other parts of the documentを作成します.
    In [40]: from openpyxl import Workbook
    
    In [48]: outwb = Workbook()     #    openpyxl.workbook.workbook.Workbook   
    
    In [49]: outwb
    Out[49]: .workbook.workbook.Workbook at 0x13665d0>

    wbObject.create_Sheet()Excelテーブルの作成
    create_sheet(title=None, index=None) method of openpyxl.workbook.workbook.Workbook instance Create a worksheet (at an optional index). :param title:optional title of the sheet:type tile:unicode:param index:optional position at which the sheet will be inserted:type index:int title(unicode):新しいExcelテーブルを作成するタイトルindex(int):新しいExcelテーブルがExcelファイルに挿入される場所
    In [62]: newSheet = outwb.create_sheet('NewSheet',0)   #    openpyxl.worksheet.worksheet.Worksheet  
    
    In [63]: type(newSheet)
    Out[63]: openpyxl.worksheet.worksheet.Worksheet

    Worksheet.append()行ごとにセルに数値を追加
    現在のテーブルの最後の行に1行のデータを追加します.反復器の実パラメータを渡す必要があります.append(iterable) method of openpyxl.worksheet.worksheet.Worksheet instance Appends a group of values at the bottom of the current sheet.
    * If it's a list: all values are added in order, starting from the first column
    * If it's a dict: values are assigned to the columns indicated by the keys (numbers or letters)
    
    :param iterable: list, range or generator, or dict containing values to append
    :type iterable: list/tuple/range/generator or dict
    
    Usage:
    
    * append(['This is A1', 'This is B1', 'This is C1'])   #      
    *#or append({'A' : 'This is A1', 'C' : 'This is C1'})  #    'A' 'C'      
    *#or append({1 : 'This is A1', 3 : 'This is C1'})      #    1、3      
    
    :raise: TypeError when iterable is neither a list/tuple nor a dict
    
    In [131]: newSheet.append(['Test',1,2,3])

    指定した列に行を追加
    In [80]: newSheet.append({'A':'Add one row'})

    指定した行に列を追加
    In [84]: newSheet.append({1:'Is A1',3:'Is C1'})

    ExcelWriter()WorkbookオブジェクトをExcelファイルに書き込む
    一般的にはWorkbok.save()メソッドはWorkbookオブジェクトの内容をExcelに書き込むことができ、openpyxlはExcelWriterというより強力なExcel書き込み実装を提供します.
    In [88]: from openpyxl.writer.excel import ExcelWriter

    class ExcelWriter(builtins.object) Write a workbook object to an Excel file.ExcelWriterオブジェクトを返します.
    In [92]: ewb = ExcelWriter(workbook=outwb)     # Workbook     ExcelWriter,   Workbook         
    
    In [95]: newSheet.title='testSheet'
    
    In [96]: outwb.get_sheet_names()
    Out[96]: ['testSheet', 'Sheet']
    
    In [97]: for i in list(range(1,11)):
       ....:     newSheet.cell('A%s' % (i)).value = i
       ....:     newSheet.append({'B':i})
       ....:
    
    In [98]: ewb.save(filename='test.xlsx')     #   Call ExcelWriterObject.save()   Workbook      。

    最後に
    上記の方法でExcelファイルのデータを処理するほか、openpyxlはExcelテーブルのスタイルを変更できる実装openpyxlを提供する.styles、これは次の編で続けます.:-)