Search code examples
pythonexcelxlrd

Getting data from an Excel file and print it to the console?


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


Solution

  • 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)