### Install Custom Python Package via URL in requirements.txt Source: https://lite.xlwings.org/dependencies Demonstrates how to specify a custom Python package for installation in xlwings Lite by providing its URL in the `requirements.txt` file. This method is used for packages not available on PyPI or Pyodide's repository. Ensure the URL points to a compatible wheel file. ```text https://myserver.com/mypackage-x.x.x-py3-none-any.whl ``` -------------------------------- ### Custom Function with Annotated Type Hints for DataFrame Conversion Source: https://lite.xlwings.org/custom_functions Shows how to use 'typing.Annotated' to specify conversion options for pandas DataFrames directly in type hints. This example sets 'index=False' for both input and output. ```python from typing import Annotated from xlwings import func import pandas as pd @func def myfunction( df: Annotated[pd.DataFrame, {"index": False}] ) -> Annotated[pd.DataFrame, {"index": False}]: # df is a DataFrame, do something with it return df ``` -------------------------------- ### Configure CORS Headers for API Server Source: https://lite.xlwings.org/web_requests Example of how to set the Access-Control-Allow-Origin header on your server to allow requests from the xlwings Lite add-in. This is necessary if your API requests are failing due to CORS errors and you control the server. ```http Access-Control-Allow-Origin: https://addin.xlwings.org ``` -------------------------------- ### Access Supabase Database with aiohttp in Python Source: https://lite.xlwings.org/databases Shows how to asynchronously fetch data from a Supabase database using the `aiohttp` library in Python. This method requires `aiohttp` and `ssl` to be added to `requirements.txt`. It handles successful responses by printing JSON data and errors by printing status codes or exception messages. ```python import aiohttp import xlwings as xw from xlwings import script @script async def db_aiohttp(book: xw.Book): key = "" # When supported, should be handled via env var url = "https://.supabase.co/rest/v1/" headers = { "apikey": key, "Authorization": f"Bearer {key}", } async with aiohttp.ClientSession() as session: try: async with session.get(url, headers=headers) as response: if response.status == 200: data = await response.json() print(data) else: print(f"Error: {response.status}") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Create Azure Container Apps Environment using Azure CLI Source: https://lite.xlwings.org/azure_container_apps Command to create a new environment for Azure Container Apps. This environment hosts the container apps and requires a name, resource group, and location. Additional options may be needed for virtual network integration. ```shell az containerapp env create \ --name $ENVIRONMENT_NAME \ --resource-group $RESOURCE_GROUP_NAME \ --location $LOCATION ``` -------------------------------- ### View Application Logs using Azure CLI Source: https://lite.xlwings.org/azure_container_apps Command to stream live logs from an Azure Container App. This is useful for monitoring the application's behavior and debugging issues during deployment or runtime. ```shell az containerapp logs show \ --name $APP_NAME \ --resource-group $RESOURCE_GROUP_NAME \ --follow ``` -------------------------------- ### Access Supabase Database with Requests in Python Source: https://lite.xlwings.org/databases Demonstrates how to fetch data from a Supabase database using the `requests` library in Python. It requires Supabase API key and project details. Handles successful responses by printing JSON data and errors by printing status codes or exception messages. ```python import requests import xlwings as xw from xlwings import script @script def db_requests(book: xw.Book): key = "" # When supported, should be handled via env var url = "https://.supabase.co/rest/v1/" headers = { "apikey": key, "Authorization": f"Bearer {key}", } try: response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() print(data) else: print(f"Error: {response.status_code}") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Custom Function with Docstrings for Function and Arguments Source: https://lite.xlwings.org/custom_functions Explains how to use docstrings for function descriptions and the '@arg' decorator for argument descriptions. These docstrings are displayed in Excel's function wizard, improving usability. ```python from xlwings import func, arg @func @arg("name", doc='A name such as "World"') def hello(name): """This is a classic Hello World example""" return f"Hello {name}!" ``` -------------------------------- ### xlwings Lite Docker Environment Variables Source: https://lite.xlwings.org/self_hosting_overview Configures the xlwings Lite Docker container using environment variables. XLWINGS_LICENSE_KEY and XLWINGS_HOSTNAME are mandatory for operation. The PORT variable is optional and defaults to 8000. ```bash # Set your xlwings license key export XLWINGS_LICENSE_KEY="your_license_key" # Set the hostname for your xlwings Lite instance export XLWINGS_HOSTNAME="xlwings-lite.mycompany.com" # Optionally set the port (defaults to 8000) export PORT="8000" ``` -------------------------------- ### Set Up Environment Variables for Azure CLI Deployment Source: https://lite.xlwings.org/azure_container_apps Defines environment variables required for deploying xlwings Lite using the Azure CLI. These variables specify resource names, location, version, and license key, some of which must be globally unique. ```shell export RESOURCE_GROUP_NAME="xlwings-lite-rg" export APP_NAME="xlwings-lite" export ENVIRONMENT_NAME="xlwings-lite-env" export LOCATION="westeurope" export XLWINGS_LITE_VERSION="1.0.0.0-17" export XLWINGS_LICENSE_KEY="your-license-key-here" ``` -------------------------------- ### Custom Function with Docstrings using Annotated Type Hints Source: https://lite.xlwings.org/custom_functions Shows how to include docstrings for arguments using 'typing.Annotated' in type hints. This approach integrates documentation directly into the function signature, making it visible in Excel's formula builder. ```python from typing import Annotated from xlwings import func @func def hello(name: Annotated[str, {"doc": 'A name such as "World"'}]): """This is a classic Hello World example""" return f"Hello {name}!" ``` -------------------------------- ### Create Azure Resource Group using Azure CLI Source: https://lite.xlwings.org/azure_container_apps Command to create a new resource group in Azure. This is a prerequisite for deploying container apps if an existing resource group is not being reused. ```shell az group create \ --name $RESOURCE_GROUP_NAME \ --location $LOCATION ``` -------------------------------- ### Create Azure Container App using Azure CLI Source: https://lite.xlwings.org/azure_container_apps Command to create the xlwings Lite container application. It specifies the app name, resource group, container image, environment, replica count, CPU/memory resources, target port, and ingress settings. ```shell az containerapp create \ --name $APP_NAME \ --resource-group $RESOURCE_GROUP_NAME \ --image docker.io/xlwings/xlwings-lite:$XLWINGS_LITE_VERSION \ --environment $ENVIRONMENT_NAME \ --min-replicas 1 \ --max-replicas 1 \ --cpu 0.5 \ --memory 1.0Gi \ --target-port 8000 \ --ingress external ``` -------------------------------- ### Update Azure Container App with Environment Variables using Azure CLI Source: https://lite.xlwings.org/azure_container_apps Command to update an existing container app with environment variables. It retrieves the Fully Qualified Domain Name (FQDN) and sets the license key and hostname environment variables for the application. ```shell FQDN=$(az containerapp show --name $APP_NAME --resource-group $RESOURCE_GROUP_NAME --query properties.configuration.ingress.fqdn -o tsv) az containerapp update \ --name $APP_NAME \ --resource-group $RESOURCE_GROUP_NAME \ --image xlwings/xlwings-lite:$XLWINGS_LITE_VERSION \ --set-env-vars XLWINGS_LICENSE_KEY=$XLWINGS_LICENSE_KEY XLWINGS_HOSTNAME=$FQDN ``` -------------------------------- ### Custom Function with Variable Arguments (Varargs) and DataFrame Conversion Source: https://lite.xlwings.org/custom_functions Shows how to handle a variable number of arguments using '*args' in a custom function. It applies a DataFrame converter with specific options to all arguments passed via '*args'. ```python from xlwings import func, arg import pandas as pd @func @arg("*args", pd.DataFrame, index=False) def concat(*args): return pd.concat(args) ``` -------------------------------- ### Adding Help URL to xlwings Custom Functions Source: https://lite.xlwings.org/custom_functions Explains how to link to external documentation for a custom function using the `help_url` option. This link appears in the Excel function wizard, providing users with more information. ```python from xlwings import func @func(help_url="https://www.xlwings.org") def hello(name): return f"Hello {name}!" ``` -------------------------------- ### Custom Function with Varargs using Annotated Type Hints Source: https://lite.xlwings.org/custom_functions Demonstrates using annotated type hints for variable arguments ('*args'). Each argument passed to 'concat' is treated as a pandas DataFrame with 'index=False' conversion applied. ```python from typing import Annotated from xlwings import func import pandas as pd @func def concat(*args: Annotated[pd.DataFrame, {"index": False}]): return pd.concat(args) ``` -------------------------------- ### Custom Function Combining Type Hints and Decorators Source: https://lite.xlwings.org/custom_functions Illustrates combining type hints with decorators for argument and return value conversion. Decorators take precedence over type hints when both are present, offering flexibility in configuration. ```python from typing import Annotated from xlwings import func, arg, ret import pandas as pd @func @arg("df", index=False) @ret(index=False) def myfunction(df: pd.DataFrame) -> pd.DataFrame: # df is a DataFrame, do something with it return df ``` -------------------------------- ### Create Basic Custom Function with xlwings Source: https://lite.xlwings.org/custom_functions Defines a simple custom function 'hello' using the '@func' decorator. It takes a 'name' argument and returns a greeting. This function can be called directly from Excel. ```python from xlwings import func @func def hello(name): return f"Hello {name}!" ``` -------------------------------- ### Creating Sub-Namespaces in xlwings Source: https://lite.xlwings.org/custom_functions Demonstrates how to create hierarchical namespaces (sub-namespaces) by including dots within the `namespace` string. This further organizes functions within Excel. ```python from xlwings import func @func(namespace="numpy.random") def standard_normal(rows, columns): rng = np.random.default_rng() return rng.standard_normal(size=(rows, columns)) ``` -------------------------------- ### Cleanup Azure Resources using Azure CLI Source: https://lite.xlwings.org/azure_container_apps Command to delete all resources associated with the xlwings Lite deployment, including the resource group and all its contents. This is a cleanup step to remove created infrastructure. ```shell az group delete --name $RESOURCE_GROUP_NAME --yes --no-wait ``` -------------------------------- ### Pull xlwings Lite Docker Image Source: https://lite.xlwings.org/self_hosting_overview Pulls the specified version of the xlwings Lite Docker image from Docker Hub. This image is designed for self-hosting and requires minimal resources. ```bash docker pull xlwings/xlwings-lite:1.0.0.0-17 ``` -------------------------------- ### Custom Function using Type Hints for pandas DataFrame Source: https://lite.xlwings.org/custom_functions Demonstrates using type hints for arguments and return values with pandas DataFrames. The function 'myfunction' expects and returns a DataFrame. xlwings automatically infers the types. ```python from xlwings import func import pandas as pd @func def myfunction(df: pd.DataFrame) -> pd.DataFrame: # df is a DataFrame, do something with it return df ``` -------------------------------- ### Grouping xlwings Custom Functions with Namespaces Source: https://lite.xlwings.org/custom_functions Shows how to organize custom functions into logical groups in Excel by assigning a namespace using the `namespace` option. This allows functions to be accessed like `NAMESPACE.FUNCTION`. ```python import numpy as np from xlwings import func @func(namespace="numpy") def standard_normal(rows, columns): rng = np.random.default_rng() return rng.standard_normal(size=(rows, columns)) ``` -------------------------------- ### Writing Date with Custom Format in xlwings Source: https://lite.xlwings.org/custom_functions Explains how to specify a custom date format when returning a date from an xlwings custom function using the `date_format` return option. Consult Excel documentation for valid format strings. ```python import datetime as dt import xlwings as xw from xlwings import func @func @ret(date_format="yyyy-m-d") def pytoday(): return dt.date.today() ``` ```python import datetime as dt import xlwings as xw from xlwings import func from typing import Annotated @func def pytoday() -> Annotated[dt.date, {"date_format": "yyyy-m-d"}]: return dt.date.today() ``` -------------------------------- ### Read CSV from GitHub API with xlwings Lite Source: https://lite.xlwings.org/web_requests Demonstrates fetching data from a public CSV file hosted on GitHub using pandas and xlwings Lite. This code works because GitHub APIs typically include the necessary CORS headers. ```python import pandas as pd df = pd.read_csv( "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv" ) ``` -------------------------------- ### Configure xlwings Lite Scripts with @script Decorator Source: https://lite.xlwings.org/custom_scripts Demonstrates how to use the @script decorator in xlwings Lite to configure which sheets are included when sending workbook content to Python. This helps optimize performance by only sending necessary data, preventing timeouts with large workbooks. The decorator accepts 'include' and 'exclude' arguments, which take lists of sheet names. ```python import xlwings as xw from xlwings import script @script(include=["Sheet1", "Sheet2"]) def hello_world(book: xw.Book): sheet = book.sheets[0] sheet["A1"].value = "Hello xlwings!" ``` -------------------------------- ### Access Environment Variable in Python with xlwings Lite Source: https://lite.xlwings.org/environment_variables This Python code snippet demonstrates how to access an environment variable, specifically 'OPENAI_API_API_KEY', using the `os.getenv()` function within an xlwings Lite script. It requires the `xlwings` library and highlights the need to handle cases where the variable might not be set. ```python 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!") ``` -------------------------------- ### Reading Datetime Arguments in xlwings Custom Functions Source: https://lite.xlwings.org/custom_functions Demonstrates how to use converters to read datetime objects passed as arguments to xlwings custom functions. Supports `dt.datetime` and `dt.date` types, and uses type hints for clarity. ```python import datetime as dt from xlwings import func @func @arg("date", dt.datetime) def myfunc(date): return date ``` ```python import datetime as dt from xlwings import func @func def myfunc(date: dt.datetime): return date ``` -------------------------------- ### Writing Current Date with xlwings Custom Function Source: https://lite.xlwings.org/custom_functions Demonstrates how to return the current date from an xlwings custom function. xlwings automatically formats the output as a date in Excel if supported. ```python import datetime as dt import xlwings as xw from xlwings import func @func def pytoday(): return dt.date.today() ``` -------------------------------- ### Custom Function with pandas DataFrame Input and Output Source: https://lite.xlwings.org/custom_functions Illustrates how to use '@arg' and '@ret' decorators with pandas DataFrames. This function 'correl2' takes a DataFrame, calculates its correlations, and returns the result without the index or header. ```python import pandas as pd from xlwings import func, arg, ret @func @arg("df", pd.DataFrame) @ret(index=False, header=False) def correl2(df): return df.corr() ``` -------------------------------- ### Reading Multiple Datetime Values with xlwings Source: https://lite.xlwings.org/custom_functions Shows how to convert a list of values to datetime objects using `xlwings.to_datetime` within a custom function. This is useful when the input range contains multiple date/time entries. ```python import datetime as dt import xlwings as xw from xlwings import func @func def myfunc(dates): dates = [xw.to_datetime(d) for d in dates] return dates ``` -------------------------------- ### Reading Date/Time Columns in Pandas DataFrame with xlwings Source: https://lite.xlwings.org/custom_functions Illustrates how to automatically parse date/time columns when reading a DataFrame into an xlwings custom function using the `parse_dates` option. This integrates seamlessly with pandas. ```python import pandas as pd from xlwings import func, arg @func @arg("df", pd.DataFrame, parse_dates=[0]) def timeseries_start(df): return df.index.min() ``` ```python from typing import Annotated import pandas as pd from xlwings import func @func def timeseries_start(df: Annotated[pd.DataFrame, {"parse_dates": [0]}]): return df.index.min() ``` -------------------------------- ### Return Dynamic Arrays from xlwings Functions Source: https://lite.xlwings.org/custom_functions Enables seamless integration with Excel's dynamic arrays by returning lists, NumPy arrays, or pandas DataFrames. Excel automatically spills these values into adjacent cells without requiring explicit code changes for array handling. ```python from xlwings import func @func def programming_languages(): return ["Python", "JavaScript"] ``` ```python import numpy as np from xlwings import func @func def standard_normal(rows, columns): rng = np.random.default_rng() return rng.standard_normal(size=(rows, columns)) ``` ```python import pandas as pd from xlwings import func @func def get_dataframe(): df = pd.DataFrame({"Language": ["Python", "JavaScript"], "Year": [1991, 1995]}) return df ``` -------------------------------- ### Define Basic xlwings Lite Custom Script Source: https://lite.xlwings.org/custom_scripts Defines a basic custom script in xlwings Lite using the @script decorator and a function argument with the xlwings.Book type hint. This script can interact with the active workbook, such as writing to a sheet. ```python import xlwings as xw from xlwings import script @script def hello_world(book: xw.Book): sheet = book.sheets[0] sheet["A1"].value = "Hello xlwings!" ``` -------------------------------- ### Configure xlwings Lite Script with Sheet Button Source: https://lite.xlwings.org/custom_scripts Configures a custom script in xlwings Lite to be triggered by clicking a shape on an Excel sheet. The @script decorator is used with a 'button' argument specifying the shape name, sheet, and cell reference for the hyperlink. ```python @script(button="[xlwings_button]Sheet1!B4", show_taskpane=True) def hello_world(book: xw.Book): # ... script logic here ... pass ``` -------------------------------- ### Handling Array Dimensions with ndim and transpose in xlwings Source: https://lite.xlwings.org/custom_functions Details the use of the `ndim` option to accept arguments of any dimension (single cell or ranges) and the `transpose` option to return a list in a vertical orientation within xlwings custom functions. ```python # Example usage of ndim and transpose would go here, but are not provided in the source text. # The description explains their functionality. ``` -------------------------------- ### Custom Function with Reusable Annotated DataFrame Type Source: https://lite.xlwings.org/custom_functions Defines a reusable type alias 'Df' using 'Annotated' for pandas DataFrames with specific conversion settings. This improves readability and allows for easier reuse of type definitions. ```python from typing import Annotated from xlwings import func import pandas as pd Df = Annotated[pd.DataFrame, {"index": False}] @func def myfunction(df: Df) -> Df: # df is a DataFrame, do something with it return df ``` -------------------------------- ### Handle Input Dimensions with ndim in xlwings Source: https://lite.xlwings.org/custom_functions Ensures function arguments are always treated as one- or two-dimensional lists, regardless of the input's Excel range dimension. This is useful when a function expects a structured list input. The `ndim` option can be applied directly or via type hints. ```python from xlwings import func, arg @func @arg("x", ndim=2) def add_one(x): return [[cell + 1 for cell in row] for row in data] ``` ```python from typing import Annotated from xlwings import func @func def add_one(x: Annotated[float, {"ndim": 2}]): return [[cell + 1 for cell in row] for row in data] ``` -------------------------------- ### Control Output Orientation with transpose in xlwings Source: https://lite.xlwings.org/custom_functions Allows vertical lists to be written to Excel as a vertical range, rather than the default horizontal orientation. This is achieved using the `transpose` option in the `@ret` decorator or via type hints. ```python from xlwings import func, ret @func @ret(transpose=True) def vertical_list(): return [1, 2, 3, 4] ``` ```python from typing import Annotated from xlwings import func @func def vertical_list() -> Annotated[list, {"transpose": True}]: return [1, 2, 3, 4] ``` -------------------------------- ### Mark Functions as Volatile in xlwings Source: https://lite.xlwings.org/custom_functions Designates a custom function to be recalculated whenever Excel performs any calculation, regardless of whether its arguments have changed. This is achieved using the `volatile=True` argument in the `@func` decorator and is useful for functions that depend on external factors like the current time. ```python import datetime as dt from xlwings import func @func(volatile=True) def last_calculated(): return f"Last calculated: {dt.datetime.now()}" ``` -------------------------------- ### Write Excel Error Cells in xlwings Source: https://lite.xlwings.org/custom_functions Writes specific Excel error strings (e.g., '#N/A', '#VALUE!') to cells, formatting them as actual error types in Excel. This allows for programmatic control over error display. Note that older Excel versions might display these as plain strings. ```python from xlwings import func @func def myfunc(x): return ["#N/A", "#VALUE!"] ``` -------------------------------- ### Read Excel Error Cells as Strings with err_to_str in xlwings Source: https://lite.xlwings.org/custom_functions Optionally reads Excel error cells (e.g., #VALUE!) as their string representation instead of converting them to None or np.nan. This is useful for inspecting or processing specific Excel errors within Python. The `err_to_str` option can be set via the `@arg` decorator or type hints. ```python from xlwings import func, arg @func @arg("x", err_to_str=True) def myfunc(x): ... ``` ```python from typing import Annotated, Any from xlwings import func @func def myfunc(x: Annotated[list[list[Any]], {"err_to_str"=True}): ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.