Tag: calc Tag: medis
tsvlookupmulti
- 医薬品の情報を表計算ソフト、ここではLibreOfficeのCalcで扱う際に、medisの医薬品データをデータベースとして利用し、これをVLOOKUPで参照したい。しかし、医薬品の情報が多く、これを表計算に読み込むと表計算ソフトが不安定になる事がある。
- そこで、参照の際にメモリの利用効率を良くするとともに、処理速度を向上する事で、利用しやすくしたいと思います。
- なお、OSはUbuntu24.04です。
Calcのマクロ追加
-
!
-
|
!
| Function TSVLookupMulti(searchKey As String, colNum As Integer) As String
Dim scriptProFactory As Object
Dim scriptProvider As Object
Dim script As Object
Dim ret As Variant
scriptProFactory = createUnoService("com.sun.star.script.provider.MasterScriptProviderFactory")
scriptProvider = scriptProFactory.createScriptProvider("")
script = scriptProvider.getScript("vnd.sun.star.script:TSVLookupMulti.py$TSVLookupMulti?language=Python&location=user")
ret = script.invoke(Array(searchKey, colNum - 1), Array(), Array())
TSVLookupMulti = ret
End Function
|
' 新しい関数 TSVLookupMulti を呼び出す
script = scriptProvider.getScript("vnd.sun.star.script:TSVLookupMulti.py$TSVLookupMulti?language=Python&location=user")
TSVLookupMulti.py の部分は、以下のPythonのスクリプトの名前に合わせます。
Pythonのコードを追加
/home/ユーザーID/.config/libreoffice/4/user/Scripts/python/TSVLookupMulti.py
-
!
-
!
-
!
-
!
-
!
-
!
| import uno
import csv
_medis_cache = None
def TSVLookupMulti(search_key, col_index):
global _medis_cache
if _medis_cache is None:
_medis_cache = {}
tsv_path = '/home/isao/Downloads/medis.tsv'
try:
with open(tsv_path, 'r', encoding='utf-8') as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
if len(row) > 0:
key = row[25] _medis_cache[key] = row
except Exception as e:
_medis_cache = {"error": "File Read Error: " + str(e)}
if "error" in _medis_cache:
return _medis_cache["error"]
if search_key in _medis_cache:
row_data = _medis_cache[search_key]
if col_index < len(row_data):
return row_data[col_index]
else:
return "Column Error: Out of Range"
return "Not Found"
|
# TSVファイルのパス
tsv_path = '/home/isao/Downloads/medis.tsv'
の部分を自分の環境に合わせます。
key = row[25] # A列(0番目)を検索キーとする
は、テキストファイルの何列目を検索に使うかにより変更します。今回は、26番目ですが、pythonの配列の要素番号が0からなので25と指定しています。