Python 导入 Excel多sheet
阅读原文时间:2023年09月02日阅读:2

Python 导入 Excel多sheet

  • 假设表格的样式如下

import os
import sys
import django

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
django.setup()

import xlrd

data = xlrd.open_workbook(filename='myexcel.xlsx')

sheet = data.sheet_by_name('sheet1')  # 名字的方式
# sheet = data.sheet_by_index(0)  # 索引的方式(从0开始)

start_row = 1  # 开始行
rows_num = sheet.nrows  # sheet行数
ncols_num = sheet.ncols  # 列数

ret = [None] * (rows_num - start_row)
for i in range(start_row, rows_num):
    ret[i - start_row] = sheet.row_values(i)

# example
for item in ret:
    name = item[0]
    age = item[1]
    hobby = item[2]
    print(name, age, hobby) # 丽萨 32 带娃