记录一下,方便以后翻阅~
开发环境:PyCharm2019.2.3 社区版
Python版本:3.8
主要代码如下:
# -*- coding: utf-8 -*-
# 作者:闲人Ne
# 格言:学到就要教人,赚到就要给人
# 描述:获取Excel数据
# 日期: 2020年12月09日
import xlrd
def read_excel(file_path):
target_excel = xlrd.open_workbook(file_path) # 打开目标文件
all_sheet_names = target_excel.sheet_names() # 获取所有sheet的名字(list类型)
print('Excel所有sheet表的名字分别是:', all_sheet_names)
sheet1_name = target_excel.sheet_names()[0] # 获取sheet1的名字
print('sheet1的名字是:', sheet1_name)
sheet1_content1 = target_excel.sheet_by_index(0) # sheet1从索引0开始
# sheet1_content2 = target_excel.sheet_by_name('Sheet1') # 另一种方法是按sheet名字获取sheet内容(不推荐,因为要输入正确的名字)
print('sheet1的名字、行数、列数分别为:', sheet1_content1.name, sheet1_content1.nrows, sheet1_content1.ncols) # 名称,行数,列数
rows = sheet1_content1.row_values(3) # sheet1第四行所有数据
cols = sheet1_content1.col_values(2) # sheet1第三列所有数据
print('第3行的数据分别为:', rows)
print('第2列的数据分别为:', cols)
print(sheet1_content1.cell(1, 0).value) # 获取单元格[第1行第0列]的内容
print(sheet1_content1.cell_value(2, 2)) # 获取单元格[第2行第2列]的内容
print(sheet1_content1.row(3)[3].value) # 获取单元格[第3行第3列]的内容
# Tips: python读取excel中单元格的内容返回的有5种类型 [0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error]
print(sheet1_content1.cell(1, 0).ctype) # 获取单元格内容的数据类型
if __name__ == '__main__':
FilePath = 'F:\\5_PyCharm_Python3.8_Workplaces\\ReadExcelInfo\\1234.xlsx'
read_excel(FilePath)
# —————— Copyright (C)2020 闲人Ne. All Rights Reserved —————— END OF FILE —————— #
运行结果如下:
先看下Excel里的数据
在看下Python运行结果: