-4

I have an excel file. How can I extract data so that in python it looks like:

list = [['Igor', '20', 'SSU]'], ['Sergay', '19', 'SSTU'], ['Nadya', '21', 'SSAU']] 

using import xlrd

  • 3
    what have you tried so far...? – mad.meesh Sep 14 '18 at 15:53
  • something like [that](https://gist.github.com/gagareg/0af52b849944eabb71865ba8d2155f27) – Igor Samarskiy Sep 14 '18 at 16:37
  • 1
    Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. [On topic](http://stackoverflow.com/help/on-topic), [how to ask](http://stackoverflow.com/help/how-to-ask), and [... the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. StackOverflow is not a design, coding, research, or tutorial resource. – Prune Sep 14 '18 at 16:43

1 Answers1

1

You can build a list using the following:

# Import:
import xlrd 

# Setting Path of File and Initializing List:
location = ("path of file") 
list = []

# Opening the Workbook and Defining Which Sheet to Use:
wb = xlrd.open_workbook(location) 
sheet = wb.sheet_by_index(0) 

# Starting at Row 0 and Column 0:
sheet.cell_value(0, 0)

# Iterating Over the Number of Rows and Appending to List:
for i in range(1, sheet.nrows + 1):
   list.append(sheet.row_values(i))

You could also loop through each of the sheets in the workbook by wrapping the wb.sheet_by_index in a for loop with the number of sheets. You may also want to run some checks to make sure the row isn't empty.

Please excuse any errors, my Python dealing with Excel is slightly rusty.

CBK
  • 660
  • 1
  • 7
  • 16
  • it does not work it shows errors `Traceback (most recent call last): File "/Users/isamarskii/Downloads/task_2/stack.py", line 17, in list.append(sheet.row_values(i)) File "/usr/local/lib/python3.7/site-packages/xlrd/sheet.py", line 492, in row_values return self._cell_values[rowx][start_colx:] IndexError: list index out of range` – Igor Samarskiy Sep 14 '18 at 16:22
  • That may be because the range. Update the range to start with 1 and try adding a print statement in the for loop to make sure things are getting added to the list. For example `print(sheet.row_values(i))` – CBK Sep 14 '18 at 16:26
  • Yes, you are right. I just changed `for i in range(1, sheet.nrows):` and now it works well. Thank you :) – Igor Samarskiy Sep 14 '18 at 16:32