文書更新:2019年07月18日(木) 午後11時16分40秒

Home > 備忘録 > 言語関連 > python に関すること > ezodf で LibreOffice データを扱う( 34 )

python3 で LibreOffice の操作をする。

必要なパッケージを install する

  1. python3-pandas を install する
  2. [root@server]# dnf install python3-pandas
  3. ezodf を install する
  4. [root@server]# pip3 install ezodf

calc データを読み込む

  1. 単純に読み込む
  2. demo.ods のデータを単純に読み込む
    [root@server]# vi demo.py
    #!/usr/bin/env python3
    # coding: utf-8
    
    import ezodf
    doc=ezodf.opendoc('path/demo.ods')
    
    for sheet in doc.sheets:	#sheet name の表示
    	print(sheet.name)
    
    sheet=doc.sheets[0]	#sheet の選択
    data=[]
    for i in range(sheet.nrows()):
    	aa=[cell.value for cell in sheet.row(i)]
    	data.append(aa)
    print(data)	#データの表示
  3. 辞書式データとして読み込む
  4. demo.ods データの1行目がデータの見出し(header)の場合、辞書型として読み込むと便利な場合がある
    [root@server]# vi demo.py
    #!/usr/bin/env python3
    # coding: utf-8
    
    import ezodf
    doc=ezodf.opendoc('path/demo.ods')
    
    sheet=doc.sheets[0]	#sheet の選択
    data = {}
    for i, row in enumerate(sheet.rows()):
        if i == 0:	#header 行の処理
            data = {cell.value:[] for cell in row}
            headers = {j:cell.value for j, cell in enumerate(row)}	#header 内容の取得
            continue
        for j, cell in enumerate(row):	#header 行以外の処理
            data[headers[j]].append(cell.value)
    print(data)