【Python】办公自动化系列之Excel

47 阅读1分钟

依赖库集

  • 依赖
workon office
pip install xlrd -i https://pypi.tuna.tsinghua.edu.cn/simple
# xlrd1.2.0之后的版本不支持xlsx格式,支持xls格式,尽量使用1.2老版本
pip uninstall xlrd
pip install xlrd==1.2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 示例
from django.http import HttpResponse
import xlrd


def index(request):
    get_sheet()
    return HttpResponse('ok')


def get_sheet():

    xlsx = xlrd.open_workbook("./20220221中文.xlsx")

    """
    获取工作表
    """
    sheets = xlsx.sheet_names()
    print(f"获取所有的sheet列表: {sheets}")
    sheet = xlsx.sheet_by_index(0)
    print(f"通过索引获取指定sheet对象: {sheet}")
    sheet = xlsx.sheet_by_name("Sheet1")
    print(f"通过名称获取指定sheet对象: {sheet}")

    """
    行操作
    """
    # 有效行数 67
    sheet.nrows
    # 指定行的有效列数 13
    sheet.row_len(7)
    # ['序号', '原岗位', '双选部门', '姓名', '性别', '联系电话', '劳动合同开始时间', ......
    sheet.row_values(1, start_colx=1, end_colx=None)
    # [text:'序号', text:'原岗位', text:'双选部门', text:'姓名', text:'性别', ......
    sheet.row(1)
    sheet.row_slice(1)
    # array('B', [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
    sheet.row_types(1, start_colx=0, end_colx=None)

    """
    列操作
    """
    # 有效列数 13
    sheet.ncols
    # ['', '原岗位', '总编辑', '项目经理', '编辑', '记者', '编辑', ......
    sheet.col_values(1, start_rowx=0, end_rowx=None)
    # [empty:'', text:'原岗位', text:'总编辑', text:'项目经理', ......
    sheet.col(1, start_rowx=0, end_rowx=None)
    sheet.col_slice(1, start_rowx=0, end_rowx=None)
    # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ......
    sheet.col_types(1, start_rowx=0, end_rowx=None)

    """
    单元格操作
    """
    sheet.cell(1, 1).value
    sheet.cell_value(1, 1)
    # 返回单元格中的数据类型 1
    sheet.cell_type(1, 1)

  • 依赖
workon office
pip install xlwt -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 示例

工具库

  • 依赖
workon office
pip install xlutils -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 示例

excel软件配置

  • office的excel将列由字母变成数字的设置 在这里插入图片描述

  • wps的excel将列由字母变成数字的设置 在这里插入图片描述