user1487000 user1487000 - 5 days ago 6
Python Question

Script to open a bunch of browser tabs, based on data from an Excel spreadsheet?

Take for example a link format of:

www.stackoverflow.com/xxxxxxx


I have an Excel spreadsheet with one of the columns as a bunch of these
xxxxxx
values. I need to pull all of them from the spreadsheet and open them as new tabs on my browser. What is the best way to go about doing this?

I've never really scripted before but I am more than willing to learn if it is necessary.

Answer

In python, use the webbrowser module to open a browser tab once you've extracted the URL.

For reading the URLs, you should either open your spreadsheet in Excel and save it in CSV format, which you can read with the csv module; or install the python module xlrd which can read real Excel spreadsheets. Assuming you install xlrd, you can extract the URLs and open them in tabs like this:

import xlrd, webbrowser

workbook = xlrd.open_workbook('websites.xls')
sheet = workbook.sheet_by_name('Sheet1')

# Suppose your URLs are in column 5, rows 2 to 30
url_column = 5
for row in range(2, 31):
    url = sheet.cell_value(row, url_column)
    webbrowser.open_new_tab(url)

Update: I now recommend openpyxl over xlrd/xlwt for working with Excel documents. It can read and write xlsx files, for example:

from openpyxl import load_workbook
wb = load_workbook(filename = 'my_document.xlsx')
sheet = wb['Sheet1']
print(sheet['D18'].value)
Comments