python操作Excel

一、读取Excel中的数据:

 1 import xlrd
 2 
 3 # excle文件对象
 4 book = xlrd.open_workbook('income.xlsx')
 5 # print(f'包含表单数量:{book.nsheets}')
 6 # print(f'表单的名称分别为:{book.sheet_names()}')
 7 
 8 # 表单对象
 9 # 表单索引从0开始,获取第一个表单对象
10 s1 = book.sheet_by_index(0)
11 # 获取名为2018的表单对象
12 # book.sheet_by_name('2018')
13 # 获取所有的表单对象,返回一个列表
14 # book.sheets()
15 
16 # print(f"表单名:{s1.name} ")
17 # print(f"表单索引:{s1.number}")
18 # print(f"表单行数:{s1.nrows}")
19 # print(f"表单列数:{s1.ncols}")
20 
21 # row 行数(行数从0开始)  colx 列数(列数从0开始)
22 # print(f"单元格A1内容是: {s1.cell_value(rowx=0, colx=0)}")
23 
24 # row_values获取指定行所有的数据,返回列表
25 # print(f'第2行的内容是:{s1.row_values(rowx=1)}')
26 
27 # col_values获取指定列所有的数据,返回列表
28 # print(f'第2列的内容是(从第二个数据开始):{s1.col_values(colx=1, start_rowx=1)}')
29 
30 # 求第一个表单所有月份的收入总和
31 incomes = s1.col_values(colx=1, start_rowx=1)
32 # print(f'2018年收入总和为:{sum(incomes)}')
33 
34 # 去掉包含星号的月份总和
35 to_sub_incomes = 0
36 # 先找到第一列月份数据,返回月份的列表
37 monthes = s1.col_values(colx=0)
38 # enumerate函数会将monthes转换成(索引,元素)组成的迭代器对象
39 for row,month in enumerate(monthes):
40     # print(row,month)
41     if type(month) is str and month.endswith('*'):
42         income = s1.cell_value(row, 1)
43         # print(month, income)
44         to_sub_incomes += income
45 print(f'2018年的真实收入为:{int(sum(incomes)-to_sub_incomes)}')

  利用for循环求所有年份的总真实收入:

 1 import xlrd
 2 
 3 book = xlrd.open_workbook("income.xlsx")
 4 
 5 # 得到所有sheet对象
 6 sheets = book.sheets()
 7 
 8 income_all_years = 0
 9 for sheet in sheets:
10     # 收入在第2列
11     incomes = sheet.col_values(colx=1,start_rowx=1)
12     # 去掉包含星号的月份收入
13     to_sub_incomes = 0
14     # 月份在第1列
15     monthes = sheet.col_values(colx=0)
16 
17     for row,month in enumerate(monthes):
18         if type(month) is str and month.endswith('*'):
19             income = sheet.cell_value(row,1)
20             print(month,income)
21             to_sub_incomes += income
22 
23     actualIncome = int(sum(incomes) - to_sub_incomes)
24     print(f"{sheet.name}年真实收入为: {actualIncome}")
25     income_all_years += actualIncome
26 
27 print(f'全部收入为{income_all_years}')

二、新建excel文件,写入数据:

 1 import openpyxl
 2 
 3 # 创建一个Excel workbook对象
 4 book = openpyxl.Workbook()
 5 
 6 # 创建时,会自动产生一个sheet,通过active获取
 7 sh = book.active
 8 
 9 # 修改当前 sheet 标题为工资表
10 sh.title = '工资表'
11 
12 # 保存文件
13 # book.save('信息.xlsx')
14 
15 # 增加一个名为 '年龄表' 的sheet,放在最后
16 sh1 = book.create_sheet('年龄表—最后')
17 
18 # 增加一个sheet,放在最前
19 sh2 = book.create_sheet('年龄表—最前', 0)
20 
21 # 增加一个 sheet,指定为第二个表单
22 sh3 = book.create_sheet('年龄表2', 1)
23 
24 # 根据名称获取某个sheet对象
25 sh_num = book['工资表']
26 
27 # 给第一个单元格写入内容
28 sh_num['A1'] = '张三'
29 
30 # 获取某个单元格内容
31 print(sh_num["A1"].value)
32 
33 # 根据行号列号,给第一个单元格写入内容
34 # 注意和xlrd不同,是从1开始
35 # sh_num.cell(2,2, value='12345')\
36 sh_num.cell(2, 2).value = '12345'
37 
38 # 根据行号列号, 获取某个单元格内容
39 print(sh_num.cell(2, 2).value)
40 
41 # 最后一定要保存文件
42 book.save('信息.xlsx')

  遍历字典写入数据:

 1 import openpyxl
 2 
 3 name_ages = {
 4     '张飞':38,
 5     '赵云':27,
 6     '许诸':36,
 7     '典韦':38,
 8     '关羽':39,
 9     '黄忠':49,
10     '徐晃':43,
11     '马超':23
12 }
13 
14 # 创建一个Excel workbook对象
15 book = openpyxl.Workbook()
16 
17 # 创建时,会自动长身一个sheeet,通过active获取
18 sh = book.active
19 
20 sh.title = '年龄表'
21 
22 # 写标题栏
23 sh['A1'] = '姓名'
24 sh['B1'] = '年龄'
25 
26 i = 2
27 for name_age in name_ages:
28     sh.cell(i, 1).value = name_age
29     sh.cell(i ,2).value = name_ages[name_age]
30     i += 1
31 
32 # 保存文件
33 book.save('信息表.xlsx')

三、修改数据:

 1 import openpyxl
 2 
 3 # 加载excel文件
 4 wb = openpyxl.load_workbook('income.xlsx')
 5 
 6 # 得到sheet对象
 7 sheet = wb['2017']
 8 
 9 sheet['A1'] = '修改一下'
10 
11 # 指定不同的文件名,可以另存为别的文件
12 wb.save('income-1.xlsx')
13 
14 # 在第2行的位置插入1行
15 sheet.insert_rows(2)
16 
17 # 在第3行的位置插入3行
18 sheet.insert_rows(3, 3)
19 
20 # 在第2列的位置插入1列
21 sheet.insert_cols(2)
22 
23 # 在第2列的位置插入3列
24 sheet.insert_cols(2, 3)
25 
26 # 指定不同的文件名,可以另存为别的文件
27 wb.save('income-1.xlsx')
28 
29 # 在第2行的位置删除1行
30 sheet.delete_rows(2)
31 
32 # 在第2行的位置删除3行
33 sheet.delete_rows(2, 3)
34 
35 # 在第2列的位置删除1列
36 sheet.delete_cols(2)
37 
38 # 在第2列的位置删除3列
39 sheet.delete_cols(2,3)

  修改表格文字颜色、字体和大小:

 1 import openpyxl
 2 from openpyxl.styles import Font, colors
 3 
 4 # 加载文件得到sheet对象
 5 wb = openpyxl.load_workbook('income.xlsx')
 6 sheet = wb['2018']
 7 
 8 # 指定单元格字体颜色,
 9 sheet['A1'].font = Font(color=colors.RED,  # 使用预置的颜色常量
10                         size=15,    # 设定文字大小
11                         bold=True,  # 设定为粗体
12                         italic=True  # 设定为斜体
13                         )
14 
15 # 也可以使用RGB数字表示的颜色
16 sheet['B1'].font = Font(color='981818')
17 
18 # 指定整行 字体风格
19 font_rows = Font(color='BD6C6C')
20 for y in range(1, 100):  # 从第1列到100列
21     sheet.cell(3, y).font = font_rows
22 
23 # 指定整列 字体风格
24 font_cols = Font(bold=True)
25 for y in range(1, 100):  # 从第1行到100行
26     sheet.cell(y, 2).font = font_cols
27 
28 # 保存文件
29 wb.save('income-2.xlsx')

  修改背景颜色:

 1 import openpyxl
 2 # 导入Font对象 和 colors 颜色常量
 3 from openpyxl.styles import PatternFill
 4 
 5 wb = openpyxl.load_workbook('income.xlsx')
 6 sheet = wb['2018']
 7 
 8 # 指定 某个单元格背景色
 9 sheet['A1'].fill = PatternFill("solid", "E39191")
10 
11 # 指定 整行 背景色, 这里指定的是第2行
12 fill = PatternFill("solid", "E39191")
13 for y in range(1, 100): # 第 1 到 100 列
14     sheet.cell(2, y).fill = fill
15 
16 # 指定 整列 背景色,略
17 
18 wb.save('income-3.xlsx')

  插入图片:

 1 import openpyxl
 2 from openpyxl.drawing.image import Image
 3 
 4 wb = openpyxl.load_workbook('income.xlsx')
 5 sheet = wb['2018']
 6 
 7 # 在第1行,第4列 的位置插入图片
 8 sheet.add_image(Image('1.png'), 'D1')
 9 
10 # 指定不同的文件名,可以另存为别的文件
11 wb.save('income-4.xlsx')
12 
13 # 如果运行提示:ImportError: You must install Pillow to fetch image objects
14 # 安装Pillow库即可
posted @ 2020-04-15 18:18  组装梦想  阅读(283)  评论(0编辑  收藏  举报