Python 办公自动化学习笔记(一)

# -*- coding: utf-8 -*-
# Version: Python 3.9.5
# Author: TRIX
# Date: 2021-09-08 17:03:29
# Use:office include: excel pdf word

#openpyxl excel表格处理
import openpyxl#需要安装 pip install openpyxl
from openpyxl import Workbook
xlsx=Workbook()#创建xlsx
xlsx=openpyxl.load_workbook(filename,data_only=False)#打开xlsx文件 类的实例化 data_only=True返回单元格的计算后的值 False将返回单元格的原字符串
xlsx.sheetnames#xlsx文件所有sheet名字组成的列表 只能引用 不能命名
xlsx.save(filename.xlsx)#程序结束时使用 只支持xlsx格式
xlsx.remove(sheet_name)#删除sheet
del xlsx['sheet_name']#删除sheet
copy_sheet=xlsx.copy_worksheet(source_xlsx)#sheet副本
sheet=xlsx.create_sheet('sheet_name',index)#新建sheet 插到索引位 索引值从0开始 不填默认插到最后
sheet=xlsx.active#激活的sheet 相当于xlsx打开后默认显示的sheet
sheet=xlsx['sheet_name']#打开xlsx中对应名字的sheet
sheet.title#表格名字 只能引用 和更改 不能命名
sheet.append(list)#写入行 从左下角第一个空单元格开始向右填充值 最多嵌套两层列表 列表中的列表表示行 列表的元素表示单元格值
for row in sheet.values:#sheet所有值数据 不包含值格式
	for value in row:pass
sheet.sheet_properties.tabColor='1072BA'#改变sheet标签颜色
sheet.max_row#最大行 只能引用 不能命名
sheet.max_column#最大列 只能引用 不能命名
sheet.row_dimensions[num_index].height = 40#行高 类似列表切片 默认12.75
sheet.column_dimensions['letter_index'].width = 30#列宽 类似列表切片 默认8.43
sheet.merge_cells('A1:C3')#合并一个矩形区域中的单元格
sheet.unmerge_cells('A1:C3')#拆分一个矩形区域中的单元格 只会保留左上角值在左上角单元格
sheet.freeze_panes='coordinate'#冻结行 列 滚动sheet时 冻结的行列不会被滚动
list(sheet.rows)#所有行 每行单元格共组成一个元组 所有元组组成一个生成器
list(sheet.columns)#所有列 每列单元格共组成一个元组 所有元组组成一个生成器
a1=sheet['A1']#单元格 'ColumnRow'
a1.value#单元格值 只能引用 不能命名 如果是日期格式 会自动转为datetime.datetime()类
a1.row#单元格行值 只能引用 不能命名
a1.column#单元格列值 只能引用 不能命名
a1.coordinate#单元格坐标 只能引用 不能命名
a1=sheet.cell(row=row_num,column=col_num,value=None)#把value写入excel 用数字来代替字母形式 数字从1开始 而不是0 value填充会覆盖单元格值 不写将返回单元格原有的值
from openpyxl.utils import get_column_letter, column_index_from_string
get_column_letter(int)#返回数字对应的列的字母
column_index_from_string('letter')#返回字母对应的列的数字
a1=value#填充值 可以输入excel公式 如 "=SUM(A1, B2)"
a1=datetime.datetime.now().strftime("%Y-%m-%d")#填充当前日期
from openpyxl.styles import Font, Border, Side, PatternFill, colors, Alignment#单元格格式
a1.font=Font(name='等线', size=24, italic=True, underline=True,color=colors.RED, bold=True)#等线 24号 加粗 斜体 下划线 红色 默认字体11
a1.alignment=Alignment(horizontal='center', vertical='right')#水平居中 竖直居右
left, right, top, bottom = [Side(style='thin', color='000000')] * 4
a1.border = Border(left=left, right=right, top=top, bottom=bottom)#边框
cell_slice=sheet['coordinate_start':'coordinate_end']
column=sheet['column_letter']
column_slice=sheet['letter_start:letter_end']
row=sheet[row_num]
row_slice=sheet[num_start:num_end]
for row in sheet.iter_rows(min_row=row_num,min_col=col_num,max_row=row_num,max_col=col_num,values_only=False):#指定行 values_only 只有值 没有坐标
	for cell in row:pass
for col in sheet.iter_cols(min_row=row_num,min_col=col_num,max_row=row_num,max_col=col_num,values_only=False):pass#指定列 values_only 只有值 没有坐标
for row in sheet.rows:
	for cell in row:
		print(cell.value,cell.coordinate)
for column in sheet.columns:
	for cell in column:
		print(cell.value,cell.coordinate)
cols_list=list(zip(*rows_list))#矩阵置换 矩阵旋转 行转列 列转行 若某一单元格缺少数据 会被舍弃这一列/行
from openpyxl.drawing.image import Image#插入图像
sheet.add_image(Image('logo.png'), 'A1')#添加到工作表并锚定在单元格旁边

#pdf处理
import PyPDF3#pip install PyPDF3
with open('file.pdf','rb') as f:#二进制读取pdf 文本提取 字符可能会异常
	pdf_reader=PyPDF3.PdfFileReader(f)#读取器
pdf_reader.numPages#页数
pdf_reader.isEncrypted#返回是否加密
pdf_reader.decrypt('str')#用str解密 只解密了pdf_file file.pdf本身仍然是加密状态
page=pdf_reader.getPage(index)#读取某页 从0开始
page.rotateClockwise(90)#顺时针旋转页面90°
page.mergePage(another_page)#将another_page叠加到page上 用于水印
page_text=page.extractText()#提取某页文本

pdf_writer=PyPDF3.PdfFileWriter()#写入器
pdf_writer.encrypt('str')#用str加密
for pagenum in range(pdf_reader.numPages):
	pdf_writer.addPage(pdf_reader.getPage(pagenum))#从已有的pdf复制每页到新建的pdf addPage只能在末尾添加页面
with open('newfile.pdf','wb') as f:
	pdf_writer.write(f)#向newfile.pdf二进制写入文本

#word
import docx#pip install python-docx
#docx: document-paragraph-run
doc=docx.Document('file.docx')#打开docx
new_doc=docx.Document()#新建docx
new_doc.add_picture('pic_file',width=docx.shared.Inches(float),height=docx.shared.Cm(float))#加图像 可选 width height 英寸 或 厘米 不填使用默认值
new_doc.add_heading(str,int)#加标题 0-4 0最大 4最小 0是Title样式 适用于顶部标题 1适用于分章标题
new_para=new_doc.add_paragraph(str,'Style')#加段落 设置段落样式 str为para里的第一个run
new_para.add_run(str)#加run
new_doc.save('file.docx')#保存docx
paragraphs_list=doc.paragraphs#段落列表
para1=doc.paragraphs[0]#第一段
para1.text#paragraph文本字符串
para1.style='Style'#设置段落样式

runs_list=para1.runs#paragraph run对象 每种格式的字符串为一个run 如 plain bold italic 为3个不同的run对象
run1=runs_list[0]#第一个run
run1.text=sting#run的文本字符串
run1.style='StyleChar'#设置run字符串样式
run1.bold=True#加粗
run1.italic=True#斜体
run1.underline=True#下划线
run1.strike=True#删除线
run1.double_strike=True#双删除线
run1.all_caps=True#大写首字母
run1.small_caps=True#大写首字母 其他字母小写 且比首字母小2点
run1.shadow=True#阴影
run1.outline=True#轮廓线 不是实心
run1.rtl=True#右到左书写
run1.imprint=True#刻入页面
run1.emboss=True#突出页面
run1.add_break()#添加换行符\n
run1.add_break(docx.text.WD_BREAK.PAGE)#添加换页符

'Style':
Normal
BodyText
BodyText2-3
Caption
Heading1-9
IntenseQuote
List
List2-3
ListBullet
ListBullet2-3
ListContinue
ListContinue2-3
ListNumber
ListNumber2-3
ListParagraph
MacroText
NoSpacing
Quote
Subtitle
TOCHeading
Title

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值