Creating a Sentiment Analysis Tool in Excel Using Hugging Face’s API

Creating a Sentiment Analysis Tool in Excel Using Hugging Face's API
Image by Author | Canva

Analyzing sentiments sounds simple until you’re faced with thousands of customer reviews. Consider you have a massive Excel sheet filled with customer reviews, and your task is to analyze their sentiment. You start reading, trying to make sense of the sentiment, but it quickly becomes overwhelming. Manually reading through each row would take hours, if not days. But what if you could automate this with AI? With Hugging Face’s API, you can integrate sentiment analysis directly into Excel using Python.

Let’s explore how to set it up.

Prerequisites

  • Python installed (3.7+ recommended)
  • Microsoft Excel
  • Basic understanding of Python & Excel

Step 1: Sign Up & Obtain a Hugging Face API Token

The first step is to generate an API token. For that:

  1. Sign up at Hugging Face.
  2. Navigate to Settings > Access Tokens and generate a new token. Set the token type to “Read.”
  3. Copy the token for later use.

Step 2: Get the xlwings Lite add-in for Excel

The xlwings Lite add-in allows us to run Python scripts in Excel Online. To install it:

  1. Open Excel.
  2. Go to Home> Add-ins> Find more add-ins at Microsoft AppSource.
  3. screenshot

  4. Search for xlwings and install it.
  5. screenshot

  6. Click on Open in Excel.
  7. screenshot

  8. Click on Allow and Continue.
  9. screenshot

Step 3: Write a Python Script for Sentiment Analysis

  1. I’ve written a Python script for you. Just copy it and make sure to replace with the API key you got in Step 1. The code includes comments to help you understand how it works.
  2. import json
    import urllib.request
    import xlwings as xw
    
    # Hugging Face API details
    API_URL = "https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english"
    HEADERS = {
       "Authorization": "Bearer " + "",  # Replace with your actual API key
       "Content-Type": "application/json"
    }
    
    def fetch_sentiment(text):
       """ Fetch sentiment prediction from Hugging Face API."""
       try:
           # Set up the API request
           req = urllib.request.Request(
               API_URL,
               data=json.dumps({"inputs": text}).encode("utf-8"),  # Convert text input to JSON format
               headers=HEADERS,
               method="POST"
           )
    
           # Send request and get a response
           with urllib.request.urlopen(req) as response:
               result = json.loads(response.read().decode())  # Decode JSON response
    
           # Extract sentiment label from response
           if isinstance(result, list) and result and isinstance(result[0], list) and result[0]:
               return result[0][0]["label"] 
           return "Error"  # Return error if response format is unexpected
       except Exception as e:
           return f"Error: {str(e)}"  # Return error message if API call fails
    
    @xw.script
    def run_sentiment_analysis(book: xw.Book):
       """ Runs sentiment analysis on Column A and writes results to Column B."""
       sheet = book.sheets.active  # Get the currently active sheet in Excel
    
       # Find the last row with data in Column A
       last_row = sheet["A1"].expand("down").last_cell.row 
    
       # Loop through all rows starting from row 2 AS row 2 contains headers
       for row in range(2, last_row + 1): 
           input_text = sheet[f"A{row}"].value  # Read text from column A
           if input_text:  # Process only if the cell is not empty
               sentiment = fetch_sentiment(input_text)  # Get sentiment prediction
               sheet[f"B{row}"].value = sentiment  # Write sentiment result to column B
    
       return "Sentiment Analysis Completed!"
  3. Open the xlwings Lite Add-in task pane. Navigate to Home > xlwings Lite.
  4. screenshot

  5. Edit or replace the already-written script with the Python script above.

Step 4: Prepare an Excel Sheet

You can choose any dataset of your choice. I’m preparing a custom Excel sheet with customer feedback to analyze sentiments. For that:


  1. screenshot

  2. Now, fill in some rows of column A.
  3. screenshot

Step 5: Run the Script in Excel

  1. Run the script from the xlwings Lite task pane:
  2. screenshot

  3. The sentiment results will appear in column B next to the feedback data as shown:
  4. screenshot

Wrapping Up

Henceforth, integrating Python in Excel using Xlwing Lite has saved you a lot of time analyzing customer reviews manually. It’s easy to scale and works in real time. You don’t need any complicated setups to use it. You can improve it by working with larger datasets, adding charts, or automating reports.

Leave a Reply

Your email address will not be published. Required fields are marked *