python 中读取excel

时间:2023-03-09 18:50:14
python 中读取excel

第一步:  先下载一个xlrd 包

#    pip install xlrd

import xlrd
from datetime import date, datetime file = '学生信息表.xlsx' def read_excel():
wb = xlrd.open_workbook(filename=file) # 打开文件
print(wb.sheet_names()) # 查看所有表的表格名字,如(Sheet1)
sheet1 = wb.sheet_by_index(0) # 通过索引获取表格
sheet2 = wb.sheet_by_name('Sheet1') # 通过表格底下的名,获取表格
print(sheet1, sheet2)
print(sheet1.name, sheet1.nrows, sheet1.ncols) # 获取表格名,行数和列数
print(sheet2.name, sheet2.nrows, sheet2.ncols)
rows = sheet1.row_values(2, 2) # 先获取第n行数据然后从第i列起一直到列的末尾的内容,只写一个数表示该行所有内容,因为源码默认列=None
cols = sheet1.col_values(2, 1) # 先获取第n列数据然后从第i行起一直到行的末尾的内容,只写一个数表示该行所有内容,因为源码默认列=None
print(rows, cols) print(sheet1.cell(2, 5).ctype) # 获取n行i列的内容
# 对于excel 表格中返回的内容有5中类型
# ctype:0 empty ,1:string, 2:number 3:date, 4:boolean, 5:error 即 date 的 ctype =3时,使用xlrd的xldate_as_tuple来处理date格式.
date_value = xlrd.xldate_as_tuple(sheet1.cell_value(2, 5), wb.datemode) # 此时date_value就是 date的数据了.
print(date_value)
print(date(*date_value[:3]))
print(date(*date_value[:3]).strftime('%Y/%m/%d'))
print(sheet1.merged_cells)