A Practical Guide to Running Local LLMs in Excel

    This guide explains how to connect a locally deployed open-source LLM to office spreadsheets so that sensitive data never leaves the machine. It covers a four-layer architecture (inference runtime, orchestration service, spreadsheet scripting, and data layer), model size selection based on VRAM and memory, 4-bit quantization, VBA request construction, streaming response parsing, and fixes for common pitfalls such as JSON escaping and UI blocking. It also outlines high-value use cases, stability and security practices, and an optional hybrid cloud setup.

    1. Why Connect a Local LLM to Your Spreadsheet

    Most teams do not want a smarter chatbot from an LLM first. They want to use one without sending data outside their environment. Contracts, financial reports, customer lists, and R&D documents become expensive to upload to external services once compliance costs are counted. Running an open-source model on a local machine or an internal server, then using an office spreadsheet as the interaction layer, is a practical compromise: employees keep the interface they already know, and inference stays local.

    From an engineering perspective, the pipeline has four layers:

    1. Inference layer: the local model runtime that loads weights, schedules compute, and exposes a unified API.
    2. Orchestration layer: a lightweight knowledge base or workspace service that handles sessions, prompt assembly, document chunking and retrieval, and wraps the raw inference API in a business-friendly form.
    3. Invocation layer: spreadsheet scripts that read cell content, send requests, parse results, and write them back.
    4. Data layer: local files, an internal document repository, or a local vector index.

    The approach described below is one concrete instance of this pipeline. The following sections go layer by layer and fill in engineering details the original outline leaves out.

    2. Environment Setup and Model Selection

    2.1 Local Inference Runtime

    Install a local model runtime on the target machine. These tools typically offer a CLI to pull models, a background service, and an API compatible with mainstream conventions. After installation, the service listens on a local port and is reachable only from that machine. To share it with other machines on the LAN, change the listen address explicitly and put a firewall and reverse proxy in front for access control. Never expose the service directly to the public internet.

    2.2 How Large a Model Do You Need

    The binding constraint is VRAM and memory capacity, not “bigger is better.” Rough guidance:

    • 7B–8B: runs on a consumer GPU or 16GB of memory, fast responses, suited to text polishing, extraction, and classification.
    • 14B: needs more VRAM or higher memory bandwidth, with a clear quality improvement.
    • 32B and above: usually requires multiple or professional GPUs, suited to complex reasoning and long-document analysis.

    Quantization is the other cost lever. 4-bit quantization cuts VRAM use to roughly one third with almost no loss of usability, at the cost of slightly reduced stability in long reasoning chains. Start with the smallest workable model to get the pipeline running, then upgrade based on task accuracy.

    2.3 What the Orchestration Layer Adds

    With only an inference API, every request is a single turn with no context and no private knowledge. Adding a local knowledge base service provides three things: multi-turn sessions, retrieval over chunked local documents injected into the prompt, and a unified internal API with key-based authentication. Configuration is simple: enter the local runtime address and model identifier in the service’s provider settings, then create an access key. No changes to the model itself are needed.

    3. Invocation Layer: Spreadsheet Scripting

    Press Alt + F11 in the spreadsheet to open the script editor, insert a module, and write the call logic. The sample below focuses on request construction and writing results back:

    1. Sub AskLocalModel()
    2. Dim q As String, body As String, r As Object
    3. Dim url As String, key As String
    4. q = ThisWorkbook.Sheets(1).Range("A2").Value
    5. If Len(Trim(q)) = 0 Then Exit Sub
    6. url = "http://127.0.0.1:3001/api/v1/workspace/demo/stream-chat"
    7. key = "locally generated access key"
    8. Set r = CreateObject("MSXML2.XMLHTTP")
    9. r.Open "POST", url, False
    10. r.setRequestHeader "Content-Type", "application/json"
    11. r.setRequestHeader "Authorization", "Bearer " & key
    12. r.setRequestHeader "accept", "text/event-stream"
    13. body = "{""message"":""" & Replace(q, """", """""") & """,""mode"":""chat""}"
    14. r.send body
    15. If r.Status = 200 Then
    16. ThisWorkbook.Sheets(1).Range("A4").Value = ExtractText(r.responseText)
    17. Else
    18. ThisWorkbook.Sheets(1).Range("A4").Value = "Request failed: " & r.Status
    19. End If
    20. End Sub

    This style of code breaks in several places. Here are the fixes:

    • Escaping: if the question contains double quotes, newlines, or backslashes, raw string concatenation corrupts the JSON. Escape consistently, or build the body with a method that serializes objects.
    • Streaming responses: the API returns an event stream, one line at a time, each shaped like data: {...}. Strip the prefix line by line, parse the nested JSON, and concatenate the incremental text instead of dumping the raw response into a cell:
    1. Function ExtractText(ByVal raw As String) As String
    2. Dim lines() As String, i As Long, s As String, out As String
    3. lines = Split(Replace(raw, vbCrLf, vbLf), vbLf)
    4. For i = 0 To UBound(lines)
    5. s = Trim(lines(i))
    6. If Left(s, 5) = "data:" Then
    7. s = Trim(Mid(s, 6))
    8. If s <> "[DONE]" Then
    9. out = out & PickText(s) ' extract the incremental text field from a single event object
    10. End If
    11. End If
    12. Next i
    13. ExtractText = out
    14. End Function
    • Synchronous blocking: a synchronous request freezes the spreadsheet UI, which is a poor experience for long answers. Switch to an asynchronous call that writes back in the event callback, or move long-running work to a background script.
    • Batch scenarios: sending synchronous requests row by row across hundreds or thousands of rows is very slow. Batch the work, rate-limit it, retry failures, and persist intermediate results to a local file so one mid-run error does not invalidate everything.

    4. Typical Use Cases

    Once the pipeline works, value comes from scenario design. Four categories tend to pay off first:

    • Structured extraction: feed an unstructured description to the model, require fixed fields, and paste the result into the adjacent column to form a reviewable intermediate table.
    • Text processing: batch polishing, summarization, translation, and tone rewriting, with humans doing final review only.
    • Classification and tagging: tag tickets and feedback against a custom label set, replacing keyword schemes that are costly to maintain.
    • Private-domain Q&A: chunk policy documents and product manuals into the knowledge base, ask questions directly in the spreadsheet, and get answers with source snippets for verification.

    Note that small local models still struggle with long reasoning chains and strict format adherence. The safer engineering pattern is “the model drafts, rules validate, humans confirm,” rather than a fully automated loop.

    5. Stability and Security

    • Network and ports: listen on the loopback address by default; if LAN sharing is required, add a reverse proxy, an access allowlist, and key validation.
    • Key management: do not hardcode keys in scripts; read them from a local config file or environment variables.
    • Resource isolation: inference saturates the GPU and memory, so deploy it separately from office workstations to avoid disrupting daily use.
    • Observability: log latency, token usage, and failure reasons for each call to tell whether the model is slow, retrieval returned nothing, or the network failed.
    • Data security: even with an entirely offline pipeline, encrypt local disks and backup media and control permissions. Data not leaving the machine does not mean there is no risk.

    6. Supplementing With Cloud Capabilities

    When local compute is insufficient or elastic concurrency is needed, a hybrid architecture works: sensitive data is masked and extracted locally, general inference tasks go to a cloud model service, the knowledge base and vector retrieval stay local, business data is archived to object storage, a message queue smooths out task spikes, and runtime health is observed through logging and monitoring with alerts. Baidu AI Cloud is typically used in these scenarios for elastic inference plus supporting storage, queue, and monitoring capabilities; refer to the official documentation for specific specs and pricing.

    7. Summary

    Connecting a local LLM to a spreadsheet means wrapping an “inference runtime + orchestration service + script invocation” pipeline in a familiar interface. Focus your effort on three things: matching model size to available compute, getting request construction and streaming parsing right, and designing key management and access control. Get those solid, and an offline assistant can reliably serve high-frequency tasks like extraction, text processing, classification, and private-domain Q&A.