"Tricks" to read Excel data file with Python

Use Python to read Excel data, save the data in each row to the dict dictionary, and finally save the dictionary to the list in.

Installation Library

python operation excel mainly used xlrd and xlwt two libraries that xlrd is read excel, xlwt is written excel library.

My demand is to read excel file, so first pip install xlrd

Obtain

I have two self Sheet , as shown:
Here Insert Picture Description
Here Insert Picture Description
You can get "Campus Files" in the following three ways:

rbook = xlrd.open_workbook('test1.xlsx')  # 打开excel,创建一个workbook对象
table = rbook.sheet_by_name("校园档案")  # 通过名称获取
# table = rbook.sheets()[1]  # 通过索引顺序获取,注意是从0开始
# table = rbook.sheet_by_index(1)  # 通过索引顺序获取

Operating line & column

  • Obtain a valid number of rows in the table
num_rows = table.nrows  # 获取该sheet中的有效行数
print("该表共有%d行" % num_rows)

Here Insert Picture Description

  • Gets the value of the second row
print(table.row_values(rowx=1))

Here Insert Picture Description

  • Gets the value of a cell, enter it coordinates
print(table.cell_value(rowx=2, colx=1))

Here Insert Picture Description
For column operation, all of the code need only above the row into col can.

Save circulation to the dictionary

Each row of data will be saved to the dict dictionary, the dictionary is added to the final list of:

# 获取一个sheet
rbook = xlrd.open_workbook('test1.xlsx')  # 打开excel,创建一个workbook对象 厦门鹭江宾馆
table = rbook.sheets()[1]  # 通过索引顺序获取,注意是从0开始

# 循环获取
list = []  # 将所有数据汇总成一个list
num_rows = table.nrows  # 获取该sheet中的有效行数
col_names = table.row_values(0)  # 获取行数下标为0也就是第一行的数据值(表头)
print("该表共有%d行" % num_rows)
for row_num in range(1, num_rows):
    row = table.row_values(row_num)  # 获取每一行的数据值
    if row:
        dict = {}
        for i in range(len(col_names)):
            dict[col_names[i]] = row[i]
        list.append(dict)
print(list)

Here Insert Picture Description

Reference article

Detailed python inside xlrd module (a)

Released eight original articles · won praise 0 · Views 621

Guess you like

Origin blog.csdn.net/qq_42491242/article/details/105076125