Environment Variables¶
xlwings Lite runs in the secure sandbox of a browser and therefore can’t access anything on your local computer. This means that it also can’t access local environment variables such as USERPROFILE
, etc.
However, you can set environment variables either in the workbook or in the add-in:
Add-in scope: stored in the browser’s local storage and available across all workbooks. However, they will be deleted when you clear the Office cache, so make a backup!
Warning
Security Warning: When using environment variables with scope “Add-in”, only open trusted workbooks from known sources. Malicious workbooks could otherwise exfiltrate these variables.
Workbook scope: stored in the current workbook.
Note: Add-in scope overrides Workbook scope.
To set an environment variable:
Provide the
Name
,Value
, andScope
and hitSave
.Restart xlwings Lite
For example, if you set the following environment variable:
Name:
OPENAI_API_KEY
Value:
your-key
You can access them like this in your code:
import os
import xlwings as xw
from xlwings import func, script
@script
def sample_script(book: xw.Book):
key = os.getenv("OPENAI_API_KEY")
if key is not None:
print(key)
else:
raise Exception("Store your OPENAI_API_KEY key under Environment Variables!")