# 最近写项目需要,通过读取excel文件导入数据至数据库
安装模块:
pip install xlrd
导入模块:
import xlrd
拿到操作excel句柄,读取excel文件:
workbook = xlrd.open_workbook(filepath)
拿到sheet句柄:
(1) 通过索引获取sheet句柄(没有名称的用这个,一般我就一个sheet)
sheet = workbook.sheet_by_index(0)
(2) 通过sheet名获取sheet句柄
sheet = workbook.sheet_by_name(sheetname)
sheet指的是这个:
获取第一行数据:
rows = sheet.row_values(0)
print(rows)
获取总行数:
print(sheet.nrows)
组合起来的写法:
import xlrd
def read_excel_data(filepath):
workbook = xlrd.open_workbook(filepath)
sheet = workbook.sheet_by_index(0)
for index in range(1, sheet.nrows):
row_value = sheet.row_values(index)
print(row_value)
if __name__ == ‘__main__‘:
read_excel_data(‘test.xlsx‘)
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did171767