热门文章

最新文章

python办公自动化之excel的操作

发布时间:2021-06-22 15:26:45

在我们日常工作中,经常会使用 Word、Excel、PPT、PDF 等办公软件但是,经常会遇到一些重复繁琐的事情,这时候手工操作显得效率极其低下;通过 Python 实现办公自动化变的很有必要


准备

使用 Python 操作 Excel 文件,常见的方式如下:

  • xlrd / xlwt

  • openpyxl

  • Pandas

  • xlsxwriter

  • xlwings

  • pywin32

xlrd 和 xlwt 是操作 Excel 文件最多的两个依赖库

其中,

xlrd 负责读取 Excel 文件,xlwt 可以写入数据到 Excel 文件

我们安装这两个依赖库

1
2
3
# 安装依赖库
pip3 install xlrd 
pip3 install xlwt 

xlrd 读取 Excel

使用 xlrd 中的 open_workbook(filepath) 打开本地一个 Excel 文件

1
2
3
4
import xlrd
 
# 打开文件,返回一个工作簿对象
wb = xlrd.open_workbook(file_path)

工作簿对象的 nsheets 属性获取 Sheet 数目,sheet_names() 方法返回所有 Sheet 名称的列表

1
2
3
4
# 统计sheet数量
sheets_num, sheets_names = wb.nsheets, wb.sheet_names()
print('sheet数量一共有:', sheets_num)
print('sheet名称分别为:', sheets_names)

筛选出工作簿中的某一个 Sheet 有 2 种方式,分别是:

  • 通过 Sheet 名称

  • 使用位置索引,从 0 开始

1
2
3
4
5
6
# 获取某一个sheet
# 通过名称或者索引获取
sheet = wb.sheet_by_index(0)
 
# sheet = wb.sheet_by_name('第一个Sheet')
print(sheet)

每一个 sheet 对象都可以利用 name、nrows、ncols 获取 Sheet 名称、行数量、列数量

另外

row_values(index)、col_values(index) 分别用于获取某一行或某一列的数据列表

1
2
3
4
5
6
7
8
9
10
11
12
13
# 获取某一个sheet中,包含的行数量、列数量
sheet_name, sheet_row_count, sheet_column_count = sheet.name, sheet.nrows, sheet.ncols
print('当前sheet名称为:', sheet_name, ",一共有:", sheet_row_count, "行;有:", sheet_column_count, "列")
 
# 单独获取某一行数据,索引从0开始
# 比如:获取第2行数据
row_datas = sheet.row_values(1)
print('第2行数据为:', row_datas)
 
# 单独获取某一列数据,索引从0开始
# 比如:获取第二列数据
column_datas = sheet.col_values(1)
print('第2列数据为:', column_datas)

单元格可以通过行索引、列索引,调用 cell(row_index,column_index) 函数获取

需要注意的是,行索引和列索引都是从 0 开始,即:0 代表第一行

在 xlrd 中,单元格的数据类型包含 6 种,用 ctype 属性对应关系如下:

  • 0  --  空(empty)

  • 1  --  字符串(string)

  • 2  --  数字(number)

  • 3  --  date(日期)

  • 4  --  boolean(布尔值)

  • 5  --  error(错误)

1
2
3
4
5
6
7
8
9
# 获取某一个单元格的数据
# 比如:获取第2行第1列的单元格的数据
one_cell = sheet.cell(1, 0)
# 单元格的值
cell_value = one_cell.value
print("单元格的值为:", cell_value)
# 单元格数据类型
cell_type = one_cell.
print("单元格数据类型为:", cell_type)

最后,如果要获取当前 Sheet 所有单元格中的数据,可以通过遍历所有行、列来操作

1
2
3
4
5
# 获取所有单元格的值
print('表格中所有数据如下:')
for r in range(sheet.nrows):
    for i in range(sheet.ncols):
        print(sheet.cell(r, i).value)

如果想实现将数据写入到 Excel 中,xlwt 就很方便了

首先,使用 xlwt 的 Workbook() 方法创建一个工作簿对象

然后,使用工作簿对象的 add_sheet(sheetname) 方法新增 Sheet

1
2
3
4
5
6
7
8
9
import xlwt
sheetname = '第一个Sheet'
 
# 创建一个工作簿对象
wb = xlwt.Workbook()
 
# 添加Sheet,通过sheet名称
sheet = wb.add_sheet(sheetname)

接着,通过 sheet 对象的 write() 方法,按照行索引和列索引,将数据写入到对应单元格中去

1
2
3
4
5
6
7
8
9
10
11
# 将数据写入到Sheet中
# 3个参数分别是:行索引(从0开始)、列索引(从0开始)、单元格的值
# 第一行第一列,写入一个数据
# 写入标题
for index, title in enumerate(self.titles):
    sheet.write(0, index, title)
 
# 写入值
for index_row, row_values in enumerate(self.values):
    for index_column, column_value in enumerate(row_values):
        sheet.write(index_row + 1, index_column, column_value)

需要注意的是,最后必须调用工作簿的 save(filepath),才能在本地生成 Excel 文件

1
2
3
# 保存文件
# 最后保存文件即可
wb.save(filepath)

进阶用法

接下来,聊聊几个常用的进阶用法

1、获取所有可见的 Sheet

在读取 Sheet 数据时,经常需要过滤隐藏的 Sheet

当 sheet 对象的 visibility 属性值为 0 时,代表此 Sheet 在工作簿中是显示的;否则被隐藏了

1
2
3
4
5
6
7
8
9
10
11
def get_all_visiable_sheets(self, wb):
    """
    获取所有可见的sheet
    :param wb:
    :return:
    """
    return list(filter(lambda item: item.visibility == 0, wb.sheets()))
 
# 1、获取所有可看见的sheet
sheet_visiable = self.get_all_visiable_sheets(wb)
print('所有可见的sheet包含:', sheet_visiable)

2、获取 Sheet 可见行或列

某一个 Sheet 中,可能存在部分行、列被隐藏了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def get_all_visiable_rows(self, sheet):
    """
    获取某一个sheet中,可见的行
    :param sheet:
    :return:
    """
    result = [index for index in range(sheet.nrows) if sheet.rowinfo_map[index].hidden == 0]
    return result
 
def get_all_visiable_columns(self, sheet):
    """
    获取某一个sheet中,可见的列
    :param sheet:
    :return:
    """
    result = [index for index in range(sheet.ncols) if sheet.colinfo_map[index].hidden == 0]
    return result

3、获取单元格的样式

以获取单元格字体颜色和背景为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def get_cell_bg_color(self, wb, sheet, row_index, col_index):
    """
    获取某一个单元格的背景颜色
    :param wb:
    :param sheet:
    :param row_index:
    :param col_index:
    :return:
    """
    xfx = sheet.cell_xf_index(row_index, col_index)
    xf = wb.xf_list[xfx]
 
    # 字体颜色
    font_color = wb.font_list[xf.font_index].colour_index
    # 背景颜色
    bg_color = xf.background.pattern_colour_index
 
    return font_color, bg_color

需要注意的是,使用 xlrd 读取单元格的样式,打开工作簿的时候需要显式定义 formatting_info = True,否则会抛出异常

1
2
3
# 注意:必须设置formatting_info=True,才能正常获取属性
wb = xlrd.open_workbook(file_path, formatting_info=True)
sheet = wb.sheet_by_index(0)

最后

搭配使用 xlrd、xlwt,基本上能完成大部分的工作,对于一些复杂的功能,比如:复制、分割、筛选等功能,可以用上 xlutils 这个依赖库

需要指出的是,这个组合对 xlsx 的兼容性不太好;如果需要操作 xlsx 文件,需要先转为 xls,然后再进行。



返回顶部