Skip to content

Instantly share code, notes, and snippets.

@jamesshah
Last active December 31, 2019 14:35
Show Gist options
  • Save jamesshah/f58a8008ae3ab031979aa8f160d5b280 to your computer and use it in GitHub Desktop.
Save jamesshah/f58a8008ae3ab031979aa8f160d5b280 to your computer and use it in GitHub Desktop.
Reading and Writing Data to and from Excel sheet in python using OpenPyxl.
# Read words from an existing excel sheet and find distant words and write it into a new excel sheet.
import openpyxl
distant_words = []
all_words = []
def get_all_words(filename, all_words):
'''Takes an excel sheet and an empty list as inputs and
returns the list of all words(values of cells) from all the columns.
'''
workbook = openpyxl.load_workbook(filename)
sheet = workbook.active
for column in range(2, sheet.max_column):
for row in range(2, sheet.max_row):
if sheet.cell(row=row, column=column).value == None:
break
else:
all_words.append(sheet.cell(row=row, column=column).value)
return all_words
def get_distant_words(filename, all_words, distant_words):
'''Takes an excel sheet, a list of all the words that the function get_all_words() returned
and an empty list as inputs and populates the empty list with distant words and writes
all these words from the list to the excel sheet
'''
workbook = openpyxl.load_workbook(filename)
sheet = workbook.active
for word in all_words:
if word not in distant_words:
distant_words.append(word)
for i in range(0, distant_words.__len__()):
sheet.cell(row=i+1, column=1).value = distant_words[i]
workbook.save(filename)
get_all_words('gre_vocab.xlsx', all_words)
get_distant_words('distant_words.xlsx', all_words, distant_words)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment