python操作excel主要用到xlrd和xlwt这两个库,即xlrd是 excel,xlwt是 excel的库,这两个适用于.xls格式有效

读操作(xlrd模块)

xlrd模块安装

在cmd窗口 pip install xlrd

封装工具(函数在下面介绍)

import xlrd
import os

class ExcelTools:
    # Excel读取相关 -------------------------------------------------------------------------------
    # 打开Excel并读取数据
    @staticmethod
    # 读取表格
    def readExcel(file, sheet_index=0,sheet_name='Sheet1'):
        data = xlrd.open_workbook(file)#文件名以及路径,如果路径或者文件名有中文给前面加一个r表示原生字符

        table = data.sheets()[0]  # 通过索引顺序获取
        # table = data.sheet_by_name(sheet_name)  # 通过名称获取
        # table = data.sheet_by_index(sheet_index) # 通过索引顺序获取

        # 以上三个函数都会返回一个xlrd.sheet.Sheet()对象

        # names = data.sheet_names()  # 返回book中所有工作表的名字
        # data.sheet_loaded(sheet_name or indx)  # 检查某个sheet是否导入完毕

        return table


    # 获取行数
    @staticmethod
    def get_row_count(table):
        return table.nrows

    # 获取列数
    @staticmethod
    def get_col_count(table):
        return table.ncols

    # 读取指定行
    @staticmethod
    def get_row_data(table, index):
        return table.row_values(index)

    # 读取指定列
    @staticmethod
    def get_col_data(table, index):
        return table.col_values(index)

    # 读取单元格数据
    @staticmethod
    def get_cell_data(table, row, col):
        return table.cell(row, col)

导入模块

import xlrd

打开Excel文件读取数据

data = xlrd.open_workbook(file)

参数:文件名以及路径(如果路径或者文件名有中文给前面加一个r表示原生字符)

sheet(工作表)操作

python 操作wps 宏 python处理wps_文件名

  1. 通过索引顺序获取sheet
table = data.sheets()[0]
  1. 通过索引顺序获取sheet
table = data.sheet_by_index(sheet_indx))
  1. 通过名称获取sheet
table = data.sheet_by_name(sheet_name)
  1. 返回book中所有工作表的名字
names = data.sheet_names()
  1. 检查某个sheet是否导入完毕
data.sheet_loaded(sheet_name or indx)

行操作

python 操作wps 宏 python处理wps_文件名_02

获取该sheet中的有效行数(属性)

nrows = table.nrows

返回由该行中所有的单元格对象组成的列表

table.row(rowx)

返回由该行中所有的单元格对象组成的列表

table.row_slice(rowx)

返回由该行中所有单元格的数据类型组成的列表

table.row_types(rowx, start_colx=0, end_colx=None)

返回由该行中所有单元格的数据组成的列表

table.row_values(rowx, start_colx=0, end_colx=None)

返回该列的有效单元格长度

table.row_len(rowx)

列操作

python 操作wps 宏 python处理wps_python 操作wps 宏_03

获取列表的有效列数(属性)

ncols = table.ncols

返回由该列中所有的单元格对象组成的列表

table.col(colx, start_rowx=0, end_rowx=None)

返回由该列中所有的单元格对象组成的列表

table.col_slice(colx, start_rowx=0, end_rowx=None)

返回由该列中所有单元格的数据类型组成的列表

table.col_types(colx, start_rowx=0, end_rowx=None)

返回由该列中所有单元格的数据组成的列表

table.col_values(colx, start_rowx=0, end_rowx=None)

单元格操作

返回单元格对象

table.cell(rowx,colx)

返回单元格中的数据类型

table.cell_type(rowx,colx)

返回单元格中的数据

table.cell_value(rowx,colx)