LoginSignup
1
5

More than 5 years have passed since last update.

エクセルファイルの数式を、文字列として取得する in Python

Posted at

Pythonで、エクセルファイルの数式を文字列として取得する方法。

調べたところ、XLSXファイルならopenpyxlというライブラリが使えるようだ。ただし弱点は、数式の結果を取得することができないところ。

XLSファイルの場合、xlrdで読み込みができるが、数式そのものを取得することができないらしい(参考)。今度は逆に、値のみ手に入る。

下記は、動作実験。
openpyxlを使って、数式付きのXSLXファイルを作成し、それを"test.xlsx"として保存。さらに、このファイルを読み込んで数式部分を文字列として取得する。

import openpyxl


# 1. Create a XLSX file #

wb = openpyxl.Workbook()
ws = wb.active

# can access a cell by:
# - cell(row = 1, column = 1)
# - cell["A1"]
for i in range(1, 11):
    # note: cells are one-based
    ws.cell(row = i, column = 1).value = i
ws["C1"].value = "=SUM(A1:A10)"

wb.save("test.xlsx")


# 2. Read and get formula 

x = openpyxl.load_workbook("test.xlsx", data_only = False)
s = x.active
print("formula at C1 is...", s["C1"].value)
# Note. openpyxl does not read the computed value of cells
1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5