python - Linux 上的 xlwings 替代方案
问题描述
我有一个小的 Python 脚本,目的是更新存储在 Onedrive 上的 Excel 工作表的某些单元格。特别是,Excel 工作簿在一张表中包含价格表,在第二张表中包含将通过 Python 自动更新的变量列表(例如,货币汇率),在第三张表中包含货币汇率历史记录(也通过 Python 进行编辑)。我想让 Raspberry Pi 定期运行并执行脚本,从而更新包含从 Rand 到 Euro 的货币汇率的字段,并将当前值插入到货币汇率的历史记录中。如果 Excel 工作表在其他设备等上打开(多个用户应该能够读取和编辑文件),该脚本应该可以正常工作而不会导致错误。在 Windows 上,我让它像这样工作:
from forex_python.converter import CurrencyRates
import xlwings as xw
from datetime import datetime
# get date and time
now = datetime.now()
current_date = now.strftime("%Y-%m-%d")
current_time = now.strftime("%H:%M:%S")
# Get current Rand to Euro conversion rate
rates = CurrencyRates()
RtoEUR = rates.get_rate("ZAR", "EUR")
# edit workbook
exl_app = xw.App(visible = False)
wb = xw.Book("/mnt/usb/LELE_expenses.xlsx")
## update currency exch. rate
sht0 = wb.sheets["Auto_upd_vals"]
sht0.range("C2").value = RtoEUR
sht1 = wb.sheets["Hist"]
last = sht1.range("B" + str(wb.sheets[0].cells.last_cell.row)) \
.end("up").row
## save current date, time and currency exch. rate
sht1.range("A" + str(last + 1)).value = current_date
sht1.range("B" + str(last + 1)).value = current_time
sht1.range("C" + str(last + 1)).value = RtoEUR
wb.save()
wb.close()
exl_app.quit()
不幸的是,无法xlwings
在 Raspbian 上安装。有没有其他方法可以做到这一点?
到目前为止的错误:
pip3 install xlwings
导致“xlwings 需要安装 Excel,因此仅适用于 Windows 和 macOS ...”运行export INSTALL_ON_LINUX=1
启用安装,但无法导入模块。大概是因为它仍然没有Excel。
解决方案
嗯,我想这比我预期的要容易:
from forex_python.converter import CurrencyRates
from openpyxl import Workbook, load_workbook
from datetime import datetime
# get date and time
now = datetime.now()
current_date = now.strftime("%Y-%m-%d")
current_time = now.strftime("%H:%M:%S")
# Get current Rand to Euro conversion rate
rates = CurrencyRates()
RtoEUR = rates.get_rate("ZAR", "EUR")
# edit workbook
wb = load_workbook("/mnt/usb/LELE_expenses.xlsx")
## update currency exchange rate
sht0 = wb["Auto_upd_vals"]
sht0["C2"].value = RtoEUR
# append currency exchange rate history
sht1 = wb["Hist"]
sht1.append([current_date, current_time, RtoEUR])
wb.save("/mnt/usb/LELE_expenses.xlsx")
wb.close()
不需要 Excel。不过,我不确定它是否会导致任何问题。
推荐阅读
- laravel - 404 在服务器上发布后找不到 laravel 5.2
- java - Spring LDAP 获取 LDAP:错误代码 32 - 0000208D NO_OBJECT
- php - PHP - 创建带有数字到字符串的数组
- python - Python Beautifulsoup 获取属性值
- django - 如果在其他模型中继承,则 Django 中父模型中的相关名称
- javascript - 如何调用嵌套 JSON 数据中的所有值(d3js)
- swift - 在数组的元素上设置观察点 - Swift
- c# - 解析时如何确定Autofac使用哪个构造函数
- java - 当我尝试填充列表视图时,我的应用程序崩溃了
- mysql - 如何使用 Dapper 将 BINARY(16) 映射到 GUID?