Python advanced (5): Python can realize the artifact of Excel automation office - openpyxl library

The third-party libraries that support both .xls and .xlsx include: xlrd, xlwings, win32com, pandas. Among them, xlrd only supports read-only operations, while other libraries can support reading and writing . This course introduces the basic usage and case application of the openpyxl library .

1. Read EXCEL file

insert image description hereinsert image description here
insert image description here

insert image description here
insert image description here
insert image description here
insert image description here

2. Write EXCEL file

insert image description here

insert image description here
insert image description here

3. EXCEL style adjustment

insert image description here
insert image description here
insert image description here

insert image description here

4. Case study

insert image description here

from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.styles import Alignment
workbook = Workbook()#新建一个工作簿
sheet1 = workbook.active
#添加两行数据
data1 = [['Rent',1000],['Gas',100],['Food',300],['Gym',50],['total',0]]
for i in data1:
    sheet1.append(i)
sheet1['B5'].value = '=SUM(B1:B4)'#增加运算公式
font = Font(name = '微软雅黑' ,size = 12)#字体格式
alignment = Alignment(horizontal = 'center',vertical = 'center',\
                      wrap_text = True)#对其格式
#获取数据范围,遍历每个单元格设置
for col in sheet1.columns:
    for cell in col:
        cell.font = font
        cell.alignment = alignment
workbook.save(filename='homework1.xlsx')

from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.styles import Alignment
workbook = Workbook()#新建一个工作簿
sheet1 = workbook.active
#添加两行数据
data1 = [['Rent',1000],['Gas',100],['Food',300],['Gym',50],['total',0]]
for i in data1:
    sheet1.append(i)
sheet1['B5'].value = '=SUM(B1:B4)'#增加运算公式
font = Font(name = '微软雅黑' ,size = 12)#字体格式
#获取数据范围,遍历每个单元格设置
for col in sheet1.columns:
    for cell in col:
        cell.font = font
font1 = Font(name = '微软雅黑' ,size = 12,bold = True)#字体格式
sheet1['A5'].font = font1
#设置数字列格式       
cell1 = sheet1['B']
alignment = Alignment(horizontal = 'right',vertical = 'center',\
                      wrap_text = True)#对其格式
sheet1.column_dimensions['B'].width = 15
for cell in cell1:
    cell.alignment=alignment
    cell.number_format='"$"#,##0.00'

#插入一行
sheet1.insert_rows(idx = 1)
data2 = ['Item','Price']
i = 0
for cell in sheet1[1]:
    cell.value = data2[i]
    cell.font = font1
    i+=1
workbook.save(filename='homework2.xlsx')    在这里插入代码片

insert image description here

from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.styles import Alignment
import datetime
workbook = Workbook()#新建一个工作簿
sheet1 = workbook.active
#添加两行数据
data1 = [['Rent',1000],['Gas',100],['Food',300],['Gym',50],['total',0]]
for i in data1:
    sheet1.append(i)
sheet1['B5'].value = '=SUM(C1:C4)'#增加运算公式,原来的B列变C列
font = Font(name = '微软雅黑' ,size = 12)#字体格式
#获取数据范围,遍历每个单元格设置
for col in sheet1.columns:
    for cell in col:
        cell.font = font
font1 = Font(name = '微软雅黑' ,size = 12,bold = True)#字体格式
sheet1['A5'].font = font1
#设置数字列格式       
cell1 = sheet1['B']
alignment = Alignment(horizontal = 'right',vertical = 'center',\
                      wrap_text = True)#对其格式
sheet1.column_dimensions['B'].width = 15
sheet1.column_dimensions['C'].width = 15#原来的B列变C列
for cell in cell1:
    cell.alignment=alignment
    cell.number_format='"$"#,##0.00'

#插入一行
sheet1.insert_rows(idx = 1)
data2 = ['Item','Price']
i = 0
for cell in sheet1[1]:
    cell.value = data2[i]
    cell.font = font1
    i+=1

#第2列左边插入一列
sheet1.insert_cols(idx = 2)
data3 = ['2020-5-20','2020-5-21','2020-5-22','2020-5-23']
sheet1['B1'] = 'Date'#列名
sheet1['B1'].font = font1#设置格式
i = 0
for row in sheet1['B2:B5']:
        for  cell in row:
            cell.value = data3[i]
            cell.value = datetime.datetime.strptime(cell.value,'%Y-%m-%d').date()#转为时间格式
            cell.number_format = 'yyyy/m/d'#修改显示格式
            cell.font = font
            i+=1
workbook.save(filename='homework3.xlsx')   在这里插入代码片

** It is not easy to sort out the courseware. I think the content of the course is good when I pass by. Please help to like and bookmark it! Thanks♪(・ω・)ノ****If you need to reprint, please indicate the source.

references:

1.https://baijiahao.baidu.com/s?id=1632485393357161183&wfr=spider&for=pc
2.https://www.cnblogs.com/liuzaoqi/p/13640847.html
3.https://blog.csdn.net/weixin_43094965/article/details/82226263
4.https://www.zhangshengrong.com/p/Ap1Zpwr7N0/
5.https://openpyxl.readthedocs.io/en/stable/tutorial.html
6.https://blog.csdn.net/BDawn/article/details/111561684

Guess you like

Origin blog.csdn.net/zxxxlh123/article/details/117254583