Skip to main content

Track Coronavirus (COVID-19) Cases in India with Google Sheets

The Coronavirus (COVID-19) tracker uses sparklines in Google Sheets to help you visualize the spread of the coronavirus outbreak across different states of India over time.


The Government of India website has a live dashboard that provides, in near real-time, the number of Coronavirus (COVID-19) cases in various states of India. This is the best resource to get updates around active COVID-19 cases in India.

COVID-19 Tracker for India

The official website provides the current data but if you were to check how the number of confirmed cases increased in India over time, there’s no historic data available. That’s one reason I built the COVID-19 Tracker with Google Sheets.

The tracker scrapes data from the official website every few minutes and uses Sparklines to help you visualize how the coronavirus outbreak is spreading in India over time. The Government has been actively publishing reports since March 10 and all the data can also be accessed through the Google Sheet.

Covid-19 India tracker

COVID-19 SHEETS TRACKER

COVID-19 JSON API

If you are a developer, I’ve also published the data as a JSON API that will provide you the latest state-wise data of COVID-19 cases as available on the Ministry of Health and Family Welfare website of India.

How the COVID-19 Tracker Works

The Coronavirus Tracker is written in Google Apps Script and it uses time-based triggers to scrape numbers from the mohfw.gov.in website every few minutes.

/**
 * Scrape the homepage of mohfw.gov.in (Ministry of Health, India)
 * website for latest numbers on Coronovirus positive cases in India
 */
const scrapeMOHWebsite = () => {
  const url = 'https://www.mohfw.gov.in/';
  const response = UrlFetchApp.fetch(url);
  const content = response.getContentText();
  return content.replace(/[\r\n]/g, '');
};

Google Apps Script doesn’t support HTML parsers like Cheerio so we had to quickly build one from scratch using regex. It grabs the HTML content of the page, looks for the table tag and then extracts data from individual cells of the table.

If they change the layout of the website, this parser is likely to break.

/**
 * Parse the webpage content and extract numbers from the HTML
 * table that contains statewise data on Covid-19 Cases in India
 */
const getCurrentCovid19Cases = (json = true) => {
  const states = {};
  const html = scrapeMOHWebsite();
  const [table] = html.match(/<div id="cases".+?>(.+)<\/div>/);
  const rows = table.match(/<tr>(.+?)<\/tr>/g);
  rows.forEach((row) => {
    const cells = row
      .match(/<td.+?>(.+?)<\/td>/g)
      .map((cell) => cell.replace(/<.+?>/g, ''));
    const [, stateName, indianNationals, foreignNationals] = cells;
    if (/[a-z\s]/i.test(stateName)) {
      states[stateName] = Number(indianNationals) + Number(foreignNationals);
    }
  });
  return json ? states : JSON.stringify(states);
};

Once we have the data in JSON format, we can easily write to a Google Spreadsheet using Apps Script. The script adds a new column per day while retaining the old data for comparison.

/**
 * Write the parsed data into a new column in Google Sheet
 * All the historic data is also preserved in the sheet.
 */
const writeNewCovid19CasesToSheets = (covid19Cases) => {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(
    'Dashboard'
  );
  const states = sheet
    .getRange(3, 1, sheet.getLastRow() - 2, 1)
    .getValues()
    .map(([state]) => [covid19Cases[state] || 0]);
  sheet
    .getRange(2, sheet.getLastColumn() + 1, states.length + 1, 1)
    .setValues([[new Date()], ...states.map((count) => [count])]);
};

The COVID-19 tracker in Google Sheets also provides a JSON API that you can use to import data directly in your apps and websites.

To publish a JSON API, we have published the script as a web app with the doGet callback function. The ContentService service returns the raw JSON output whenever an external app invokes the Google script URL.

const doGet = () => {
  const key = 'Covid19India';
  const cache = CacheService.getScriptCache();
  let data = cache.get(key);
  if (data === null) {
    data = getCurrentCovid19Cases(false);
    cache.put(key, data, 21600);
  }
  return ContentService.createTextOutput(data).setMimeType(
    ContentService.MimeType.JSON
  );
};

All the code is open-source and you are free to use in any project.

Comments

Popular posts from this blog

The Most Awesome Online Teachers for Learning Web Development

For the past few months, I have been on a learning spree looking to enhance my existing coding skills and also learn new programming languages and frameworks. In this process, I have watched a countless number of video tutorials and online courses that pertain to programming and, specifically, web development. In my quest to become a better developer, I’ve come across several awesome “teachers” who aren’t just excellent programmers but awesome educators and have the art of explaining complex and difficult concepts. Learn Modern Web Programming with the Best Online Teachers This is an attempt to highlight the best instructors on the Internet for JavaScript, React, Redux, Node.js, Firebase (database and storage), Docker, Google Golang, Typescript, Flutter (for mobile app development), Dart, Git, Webpack and Parcel bundler. I’ve taken courses by every single instructor mentioned here ( PDF ) and recommend them highly. Language / Platform Teacher / Course React.js Andrew...

How to Test your Eyes using the Computer

They say that you should get your eyes checked every two years but if haven’t had the chance to see a doctor all this time, you can test your vision on your computer as well. Of course these self eye tests are no substitute for visiting your doctor but if you follow the steps well, you may get some idea about how good (or bad) your vision is.  Test your Eyes Online with the Snellen Eye Chart The Snellen Eye Chart Most of us are familiar with the Snellen Chart that has rows of alphabets of different sizes – you read these letters from a distance, usually twenty feet, and the smallest row that you can recognize accurately indicates whether you have normal vision or not. The various eye testing tools that are available online make use of the same Snellen chart. Test your Eyesight Online You should start with University at Buffalo’s  IVAC tool . Use a physical ruler to measure the length of the line on the screen (the length will vary depending on your screen resolution). Also mea...

Play any YouTube Playlist with VLC Media Player

Do you know that  VLC Media Player , the world’s favorite video player that supports nearly every video format, can also play YouTube videos on your desktop without requiring the web browser or the Adobe Flash player. To get started, open the VLC player, press Ctrl+N to open the Network URL dialog and paste any YouTube video URL in the input box. The Benefits of Watching YouTube Videos with VLC The streaming videos will play inside VLC Media Player just like any other local video file while offering some additional benefits not available inside the standard YouTube player. For instance: You can choose Video -> Always on Top inside VLC and the YouTube video window will stick to the foreground while you work on other tasks. Press the Loop button in the player controls and the YouTube video will play non-stop in a loop (also possible with  Chrome add-ons ). You can change the Playback speed of the YouTube video and make it run slower or faster than the normal speed. Use the To...