Skip to main content
TutorialGoogle SheetsUpdated January 2025

How to Get Real-Time Oil Prices in Google Sheets

Learn 5 different methods to import live WTI, Brent crude, natural gas, and diesel prices into Google Sheets. Includes copy-paste code, auto-refresh setup, and a free template.

By Oil Price API Team|15 min read|Last updated: January 2025

If you work with fuel budgets, energy trading, logistics, or commodity analysis, you know the pain of manually updating oil prices in your spreadsheets. Copying prices from websites is tedious, error-prone, and often means working with stale data.

This guide shows you how to automatically pull live oil prices into Google Sheets—so your spreadsheet always has the latest WTI, Brent crude, natural gas, coal, and diesel prices without any manual work.

We'll cover five different methods, from zero-code solutions to powerful Apps Script integrations. By the end, you'll have live commodity prices updating in your spreadsheet on autopilot.

Method Comparison: Which One Should You Use?

MethodDifficultyAuto-RefreshCostBest For
Apps ScriptEasy (copy-paste)Yes (5 min to daily)Free trial, then $19/moMost users (Recommended)
Add-onVery Easy (no code)Yes (built-in)Paid plans onlyNon-technical users
IMPORTDATAEasyLimitedFree (limited data)Quick tests
ManualVery EasyNoFreeOne-time lookups
Zapier/MakeMediumYesAPI + Zapier costsEnterprise workflows

Our recommendation: Start with the Apps Script method. It takes 5 minutes to set up, gives you full control over refresh frequency, and works with our free trial.

Method 1: Apps Script Custom Function (Recommended)

This is the most flexible and powerful method. You'll create a custom function that works just like built-in formulas (SUM, AVERAGE, etc.) but fetches live oil prices from our API.

1Get Your Free API Key

Sign up at oilpriceapi.com to get your API key. The free trial includes 10,000 requests over 7 days—plenty to test and get started.

Get Free API Key

2Open Apps Script Editor

  1. Open your Google Sheets spreadsheet
  2. Click Extensions in the menu bar
  3. Select Apps Script
  4. Delete any existing code in the editor

3Paste This Code

Copy the entire code block below and paste it into the Apps Script editor. Replace YOUR_API_KEY with your actual API key.

/**
 * Gets the current price for a commodity from Oil Price API
 * @param {string} commodityCode - The commodity code (e.g., "WTI_USD", "BRENT_USD")
 * @return {number} The current price
 * @customfunction
 */
function OIL_PRICE(commodityCode) {
  var API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
  var url = 'https://api.oilpriceapi.com/v1/prices/latest?by_code=' + commodityCode;

  var options = {
    'method': 'GET',
    'headers': {
      'Authorization': 'Token ' + API_KEY,
      'Content-Type': 'application/json'
    },
    'muteHttpExceptions': true
  };

  try {
    var response = UrlFetchApp.fetch(url, options);
    var responseCode = response.getResponseCode();

    if (responseCode !== 200) {
      return 'Error: ' + responseCode;
    }

    var data = JSON.parse(response.getContentText());

    if (data.status === 'success' && data.data && data.data.price) {
      return data.data.price;
    } else {
      return 'Error: Invalid response';
    }
  } catch (error) {
    return 'Error: ' + error.message;
  }
}

/**
 * Gets diesel price for a US state
 * @param {string} stateCode - Two-letter state code (e.g., "TX", "CA")
 * @return {number} The current diesel price per gallon
 * @customfunction
 */
function DIESEL_PRICE(stateCode) {
  var API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
  var url = 'https://api.oilpriceapi.com/v1/diesel-prices?state=' + stateCode;

  var options = {
    'method': 'GET',
    'headers': {
      'Authorization': 'Token ' + API_KEY,
      'Content-Type': 'application/json'
    },
    'muteHttpExceptions': true
  };

  try {
    var response = UrlFetchApp.fetch(url, options);
    var data = JSON.parse(response.getContentText());

    if (data.data && data.data.regional_average) {
      return data.data.regional_average.price;
    } else {
      return 'Error: Invalid response';
    }
  } catch (error) {
    return 'Error: ' + error.message;
  }
}

/**
 * Force refresh all custom functions
 * Run this manually or set up a trigger
 */
function refreshAllPrices() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getDataRange();
  var values = range.getValues();
  range.setValues(values);
}

4Save and Use the Function

  1. Press Ctrl+S (or Cmd+S on Mac) to save
  2. Go back to your spreadsheet
  3. In any cell, type: =OIL_PRICE("WTI_USD")
  4. Press Enter—the current WTI price should appear!

Example formulas:

=OIL_PRICE("WTI_USD") → 72.45
=OIL_PRICE("BRENT_USD") → 76.32
=OIL_PRICE("NATURAL_GAS") → 2.89
=DIESEL_PRICE("TX") → 3.12
=DIESEL_PRICE("CA") → 5.23

Method 2: Google Sheets Add-on (No Code)

If you prefer not to touch any code, our Google Sheets add-on provides a point-and-click interface for importing oil prices. Available for paid plan subscribers.

How to Install the Add-on

  1. Open Google Sheets and click Extensions → Add-ons → Get add-ons
  2. Search for "Oil Price API" in the marketplace
  3. Click Install and authorize the add-on
  4. Open the add-on from Extensions → Oil Price API → Open sidebar
  5. Enter your API key in the sidebar
  6. Select commodities and click "Insert Prices"

Note: The add-on requires a paid subscription ($19/month or higher). For free trial users, we recommend the Apps Script method above.

Method 3: IMPORTDATA Function (Simple but Limited)

Google Sheets' built-in IMPORTDATA function can fetch data from URLs, but it has limitations for API authentication. This method works for public endpoints only.

Basic IMPORTDATA Usage

While IMPORTDATA doesn't support API authentication headers, you can use it with our demo endpoints:

=IMPORTDATA("https://api.oilpriceapi.com/v1/demo/wti")

Limitations: IMPORTDATA is rate-limited by Google and doesn't support authenticated API calls. For reliable, production use, we strongly recommend the Apps Script method instead.

Method 4: Manual Reference (No Cost)

The simplest method is to use our public reference and documentation pages to identify the commodity codes you need. Best for occasional setup work where automation isn't necessary yet.

Method 5: Zapier/Make Integration (Enterprise)

For complex workflows that need to push oil prices to multiple destinations (Google Sheets, Slack, email, databases), consider using Zapier or Make (formerly Integromat).

Example Workflow

  1. Trigger: Schedule (every hour)
  2. Action: HTTP Request to Oil Price API
  3. Action: Parse JSON response
  4. Action: Update Google Sheets row
  5. Action: Send Slack notification if price exceeds threshold

This method requires a Zapier/Make subscription plus our API. Best for enterprise users who need complex automation across multiple tools.

How to Set Up Auto-Refresh

Custom functions in Google Sheets don't automatically refresh. To keep your prices updated, you need to set up a time-based trigger in Apps Script.

Step 1: Open Triggers

  1. In Apps Script, click the clock icon (Triggers) in the left sidebar
  2. Click + Add Trigger in the bottom right

Step 2: Configure the Trigger

  • Choose function: refreshAllPrices
  • Event source: Time-driven
  • Type: Minutes timer, Hour timer, or Day timer
  • Interval: Every 5 minutes, Every hour, etc.

Pro Tip: Use "Every hour" for most use cases. This balances freshness with API usage. With 10,000 requests/month (Hobby plan), hourly updates support 13+ commodities per spreadsheet.

Real-World Use Cases

🚚

Fleet Fuel Cost Tracking

A logistics company tracks diesel prices across their 12-state operation. The spreadsheet auto-updates every morning, helping dispatch adjust fuel budgets before trucks roll out.

=DIESEL_PRICE("TX") * D2
📊

WTI-Brent Spread Monitoring

An energy trader monitors the spread between WTI and Brent crude. When the spread exceeds $4, conditional formatting highlights the cell and triggers an email alert.

=OIL_PRICE("BRENT_USD") - OIL_PRICE("WTI_USD")
💼

Client Reporting Dashboards

An energy consultant creates shared Google Sheets for each client showing their relevant commodity prices. Clients see live data without needing expensive Bloomberg terminals.

=SPARKLINE(B2:B30)
📱

Mobile Price Alerts

A procurement manager uses Google Sheets on their phone to check fuel prices before placing bulk orders. The same sheet works seamlessly on desktop, tablet, and mobile.

Works on iOS, Android, and web

Complete Commodity Code Reference

Crude Oil

WTI_USDWest Texas Intermediate
BRENT_USDBrent Crude (ICE)
DUBAI_USDDubai/Oman
OPEC_BASKETOPEC Reference Basket
URALS_USDRussian Urals
WCS_USDWestern Canadian Select

Natural Gas

NATURAL_GASHenry Hub (USD/MMBtu)
TTF_EURDutch TTF (EUR/MWh)
UK_NBPUK NBP (GBp/therm)
JKM_USDJapan Korea Marker

Refined Products

HEATING_OILNY Harbor Heating Oil
GASOLINE_RBOBRBOB Gasoline
JET_FUELJet Fuel (Kerosene)
PROPANEPropane

Other Commodities

COAL_USDNewcastle Coal
GOLD_USDGold (per oz)
SILVER_USDSilver (per oz)
COPPER_USDCopper

Troubleshooting Common Issues

⚠️"Error: Exception: Request failed"

Your API key is invalid or wasn't replaced in the code.

Fix: Open Apps Script and replace YOUR_API_KEY with your actual API key from your dashboard.

⚠️"#ERROR!" appears in cell

The custom function isn't recognized by Google Sheets.

Fix: Make sure you saved the Apps Script code (Ctrl+S). Try closing and reopening the spreadsheet.

⚠️"Loading..." never completes

Google Sheets is having trouble executing the script.

Fix: Check Apps Script's execution log (View → Executions). You may need to re-authorize the script—look for a yellow banner at the top.

⚠️"Error: 429" (Rate Limit)

You've exceeded your API request limit.

Fix: Reduce refresh frequency (use hourly instead of every 5 minutes) orupgrade your plan.

⚠️Prices not updating automatically

Custom functions don't auto-refresh by default.

Fix: Set up a time-based trigger as shown in the Auto-Refresh section.

⚠️"Authorization required" popup

The script needs permission to make external API calls.

Fix: Click "Review permissions" and authorize the script. This is safe—the script only makes calls to oilpriceapi.com.

Frequently Asked Questions

How do I get oil prices in Google Sheets?

Use our Apps Script custom function. Go to Extensions → Apps Script, paste the OIL_PRICE function code, save, then use =OIL_PRICE("WTI_USD") in any cell to get real-time oil prices.

Is getting oil prices in Google Sheets free?

Yes, we offer a free 7-day trial with 10,000 API requests. This is enough for testing and light usage. Paid plans start at $19/month for 10,000 requests.

What commodities can I get in Google Sheets?

You can get WTI Crude, Brent Crude, Dubai Crude, OPEC Basket, Natural Gas (Henry Hub), Coal, Heating Oil, Gasoline, and diesel prices for all 50 US states—over 40 commodities total.

How often do oil prices update in Google Sheets?

With Apps Script triggers, you can set prices to update every 5 minutes, hourly, or daily. WTI and Brent prices update on our servers every 5 minutes during market hours.

Can I use this on the Google Sheets mobile app?

Yes! Once you set up the custom function on desktop, it works on any device including the Google Sheets mobile app for iOS and Android.

Do I need programming knowledge?

No programming knowledge is required. Just copy and paste our ready-to-use code into Apps Script and replace the API key placeholder with your actual key.

Can I share the spreadsheet with colleagues?

Yes! The custom functions work for anyone who has access to the spreadsheet. They'll see the live prices without needing their own API key—your key is embedded in the script.

What's the difference between Google Sheets and Excel?

Both work great for oil prices. Google Sheets is cloud-based and works on any device. Excel requires our desktop add-in. Choose based on your existing workflow.

Ready to Get Started?

Get your free API key and start using live oil prices in Google Sheets today. Takes less than 5 minutes to set up.

Related Articles