Cheap VPS host selection
Provide server host evaluation information

How to read an xlsx file in Python How to read xlsx data in python

Xlsx is also a file type in excel files. We have learned to read excel files using Python before. In program development, it always involves reading files. How does Python read xlsx files? Let's have a look.

 

1、 Preparatory work

First, we need to have an xlsx file and put it in the code editor we use.

2、 Xlrd library reading

This library allows us to read excel files in Python. Before using it, we need to install it. The installation method is as follows:

 pip install xlrd

After installation, you can use it to read files. Specific examples are as follows:

 import  xlrd Open Excel wb  =  xlrd.text(hh.xlsx') Locate Sheet by Workbook sh  =  wb.sheet_by_name(' TestUserLogin ') print (sh.nrows) # Number of valid data rows print (sh.ncols) # Number of valid data columns print (sh.cell( zero , zero ). value) # Output the values in the first row and column print (sh.row_values( zero ))#Output all values in the first row Combine data and titles into a dictionary print (dict( zip (sh.row_values( zero ),sh.row_values( one )))) Traverse excel and print all data for  i  in  range(sh.nrows):    print (sh.row_values(i))

In the code, first import the library we just installed, open the Excel table we just talked about using, locate the table using the way of locating the workbook, read some data rows and columns, use the for loop to traverse the Excel table, and finally print all the data.

3、 Pandas library reading

Pandas library is a library for data processing, which can facilitate us to process data in excel. Before using it, we need to install it. The installation command is as follows:

 pip install pandas

Specific examples are as follows:

 import  pandas as pd  df  =  pd.read_excel(hh.xlsx') data = df.values print ( "Get all values: \n {}" .format(data))

In the code, the pandas library is directly imported to obtain all data in the excel table at one time.

Do not reprint without permission: Cheap VPS evaluation » How to read an xlsx file in Python How to read xlsx data in python