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. Use this for secrets (e.g., API keys). However, they will be deleted when you clear the Office cache, so make a backup!

  • Workbook scope: stored in the current workbook so don’t use this for secrets.

Note

  • Add-in scope overrides Workbook scope.

  • Environment variables with add-in scope are stored in the browser’s local storage and never leave your machine.

To set an environment variable:

  • Provide the Name, Value, and Scope and hit Save.

  • 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!")