python openpyxl 简单使用

官方文档地址:https://openpyxl.readthedocs.io/en/stable/tutorial.html

1. 加载excel

import openpyxl
from openpyxl.utils import get_column_letter,column_index_from_string
from openpyxl.styles import Font,PatternFill
import os


# 加载example.xlsx,参数 data_only=False 表示如果单元格是公式,则显示公式,而不是公式的计算结果
wb = openpyxl.load_workbook('example.xlsx',data_only=False)

# 列出所有sheet名称,返回一个list
sheets = wb.sheetnames
print('Sheets:',sheets)

# 获取当前激活的 sheet
activesheet = wb.active  # 获取特定名字的 sheet 可以这样做: ws = wb['sheetName']
# 获取 sheet 的名称
print(activesheet.title)

# 获取单元格对象
a1 = activesheet['A1']

# 单元格的值
print(a1.value)

# 获取单元格对象的行列, 以及单元格名称,coordinate 返回单元格的名称。
print(a1.row,a1.column,a1.coordinate,sep=',')

# 根据 行列 来定位一个单元格
a2 = activesheet.cell(row=2,column=2)
print('A2 value:',a2.value)

# 获取表中的最大行数和列数
highest = activesheet.max_row
wid = activesheet.max_column
print('MaxRow,MaxCol:',highest,wid)

# 转换列名和数字
print(get_column_letter(77), column_index_from_string('AA'))

# 使用切片来获取一个区域,返回元组形式
field = activesheet['A1':'C3']  # 也可以写成这种形式: "A1:C3"
print('Field:',field)

for x in activesheet['A1':'C3']:  # 先获取元组的元素:一整行数据
    for y in x:                   # 再获取每行中的每一个元素:单元格
        print(y.coordinate,y.value)


wb.save('new.xlsx')   # 保存文件

2. 创建新的excel文件

import openpyxl
from openpyxl.utils import get_column_letter,column_index_from_string
from openpyxl.styles import Font,PatternFill
import os


# 创建写入excel
if os.path.exists('new.xlsx'):
    os.unlink('new.xlsx')   # 如果存在 new.xlsx ,先删除

# 创建工作簿对象
wb = openpyxl.Workbook()

# 获取激活的表单
active = wb.active

# 获取sheet名称
print(active.title)

# 给sheet重命名
active.title = 'Abc'

# 创建带索引的 sheet,也就是 sheet 表单的顺序,索引为 1 代表放在第一个
wb.create_sheet(index=1,title='New_sheet')
wb.create_sheet(index=2,title='New_sheet2')

# 获取所有sheet名
sheets = wb.get_sheet_names
print(sheets)

# 删除一个工作表
wb.remove(wb['New_sheet2'])
for x in range(1,100):     # 写入excel
    active.cell(row=x,column=1,value=x)

# 设置单元格样式
active.row_dimensions[1].height = 30   # 设置行高
active.column_dimensions['A'].width = 30  # 设置列宽

# 合并单元格并赋值
active.merge_cells('A1:C1')
active['A1'] = 'hebkdjyrge'

# 拆分单元格
active.unmerge_cells('A1:C1')


# 冻结行列
active.freeze_panes = 'A3'  # 冻结 A 列之前的列,和第 3 行之前的行。因为 A 列之前没有列,所以不冻结任何列。只冻结第1,2行
active.freeze_panes = 'C3'  # 会冻结 A,B列,冻结 1,2 行。
active.freeze_panes = None  # 会取消冻结

# 添加过滤(可能不会生效)
active.auto_filter.ref = 'A1:B5'  # 对某个区域设置过滤选项
active.auto_filter.add_filter_column(1, ['wang'])  # 过滤并选取第 1 列(索引从0开始)即 B 列数据为 'wang' 的数据。

# 设置排序(可能不会生效)
active.auto_filter.add_sort_condition(ref='A1:A7', descending=False)


# 设置字体
geui = Font(size=15,name='Arial',bold=True,italic=False,color='FFFFFF')
colorr = PatternFill('solid',bgColor='4F4F4F')
active['A1'].fill = colorr
active['A1'].font = geui

# 设置内容对齐方式
from xl.styles import Alignment
active['A3'].alignment = Alignment(horizontal='right', vertical='center')

# 创建图表
for i in range(1,11):
    active['A'+str(i)] = i
refObj = openpyxl.chart.Reference(active, min_row=1, min_col=1, max_row=10, max_col=1)  # 获取某个表中的数据范围
seriesObj = openpyxl.chart.Series(refObj, title='First series')  # 图表的数据系列
chartObj = openpyxl.chart.BarChart()  # 创建柱状图
chartObj.title = 'My Chart'  # 图表标题
chartObj.append(seriesObj)  # 将数据添加到图表上

active.add_chart(chartObj, 'C5')  # C5表示图表放置的位置

wb.save('new.xlsx')   # 保存文件

3. 读取Excel的某列

import openpyxl as xl


wb = xl.load_workbook('t1.xlsx')
s1 = wb['Sheet1']

# 获取 sheet 的第 1 列,1-5 行的数据; min_* 参数不写,则默认从第一行/列 开始;max_* 参数不写,则默认到达最后一行/列。values_only=True 可以获取单元格的值,否则获取的是单元格对象
values = list(s1.iter_cols(min_col=1, max_col=1, min_row=1, max_row=5, values_only=True))  # 相应的,也有 iter_rows 方法
print(values)

first_column = list(s1.columns)[0]  # sheet.columns 是对 sheet.iter_cols 的封装,可以返回所有列的单元格对象;相应的,也有 sheet.rows 方法
print(first_column)

4. 设置边框

import openpyxl

from openpyxl import load_workbook
from openpyxl.styles import Border, Side, colors,Font,PatternFill


excel_address = "112report.xlsx"
wb = load_workbook(excel_address)
sht = wb.worksheets[0]

sht["D5"] = "测试"
# 全边框
border_all = Border(left=Side(style='thin', color=colors.BLACK),
                    right=Side(style='thin', color=colors.BLACK),
                    top=Side(style='thin', color=colors.BLACK),
                    bottom=Side(style='thin', color=colors.BLACK))
# 无上边框
border_set = Border(left=Side(style='thin', color=colors.BLACK),
                    right=Side(style='thin', color=colors.BLACK),
                    top=Side(style='thin', color=colors.BLACK),
                    bottom=Side(style='thin', color=colors.BLACK))
# 背景色
fill_1 = PatternFill("solid", fgColor="E6E6E6")

# 字体
title = Font(name='Arial',bold=True)
con = Font(name='Arial',bold=False)

sht["D5"].border = border_set
sht["D5"].fill = fill_1
sht["D5"].font = title


wb.save(excel_address)
posted @ 2019-12-09 15:27  wztshine  阅读(1613)  评论(0编辑  收藏  举报