-2

I developed the following code to extract data from an Excel file and print it in the console. This code is reading the data as intended and printing the content read into the console, but I want to print it differently. Instead of printing row by row, I want to print column by column and also, print every column as a new column in the console instead of as a single column as seen in the picture below the code.

import xlrd

# Give the location of the file
location = ("C:/Users/congo/Documents/PythonScriptTest.xlsx")

# To open workbook
workbook = xlrd.open_workbook(location)
sheet = workbook.sheet_by_index(0)

# Looping through rows and columns of excel file
for i in range(sheet.nrows):
    for j in range(sheet.ncols):
        print(sheet.cell_value(i, j))

The script is getting the data correctly and printing it like seen in the following picture, but I want to print it exactly as seen in the Excel file. enter image description here

This is how the Excel file and how I also wish to print the items in the console. What library should I use to accomplish this? I appreciate the help.

enter image description here

  • 2
    Please don't post screenshots. Your question should be self-contained in appropriately-formatted text – roganjosh Feb 12 '20 at 21:28
  • 1
    [Discourage screenshots of code and/or errors](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors) – martineau Feb 12 '20 at 21:36
  • Why are you using xlrd if your file is in the XLSX format? – AMC Feb 13 '20 at 01:40

2 Answers2

2

Pandas is a very good tool to import excel data into Python. This should work:

import pandas as pd

df = pd.read_excel("C:/Users/congo/Documents/PythonScriptTest.xlsx")

print(df)
lsterzinger
  • 687
  • 5
  • 22
1

You are iterating over rows and columns and you are printing every element, to print the full row you can do something like

# Looping through rows and columns of excel file
for i in range(sheet.nrows):
    for j in range(sheet.ncols):
        print(sheet.cell_value(i, j), end='\t')
    print('\n')

An alternative consists in using:

print(pd.read_excel('PythonScriptTest.xlsx'))
abc
  • 11,579
  • 2
  • 26
  • 51