python中自动化办公 【笔记】

00读取csv文件

import csv
def readCsv(path):
    infolist = []
    with open (path,"r") as f:

        allFileInfo = csv.reader(f)
        print(allFileInfo)
        for row in allFileInfo:
            infolist.append(row)
    return infolist

path =r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\2、读写csv文件\000001.csv"
info = readCsv(path)
# [[],[],[]]





01写csv文件

import csv

def writeCsv(path,data):
    with open(path,"w")as f:
        write = csv.writer(f)

        for rowData in data:
            print("*********")
            write.writerow(rowData)



path =r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\2、读写csv文件\000003.csv"
writeCsv(path, [[1,2,3],[4,5,6],[7,8,9]])

02读取pdf文件

import sys
import importlib
importlib.reload(sys)

from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed

def readPDF(path,topath):
    #以二进制打开pdf文件
    f = open(path,"rb")
    #创建一个PDF文档分析器
    parse = PDFParser(f)

    #创建PDF文档
    pdfFile = PDFDocument()

    #链接 分析器与文档对象 互相连接
    parse.set_document(pdfFile)
    pdfFile.set_parser(parse)
    #提供初始化密码
    pdfFile.initialize()
    #检测文档是否提供txt转换
    if not pdfFile.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        #解析数据
        #数据管理器
        manager = PDFResourceManager()
        #创建一个PDF设备的对象
        laparams= LAParams()
        device = PDFPageAggregator(manager,laparams=laparams)

        #解释器对象
        interpreter = PDFPageInterpreter(manager,device)

        #开始循环处理,每次处理一页
        for page in pdfFile.get_pages():
            interpreter.process_page(page)
            layout =device.get_result()
            for x in layout:
                if (isinstance(x,LTTextBoxHorizontal)):
                    with open(topath,"a")as f:
                        str = x.get_text()

                        # print(str)
                        f.write(str+"\n")



topath=r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\a.txt"
path =r"D:\xiazaipan\第1章  Python语言基础\16、py2与py3的区别和测试\0-作业\文件的封装\sunck.pdf"
readPDF(path,topath)

03播放音乐

#pip install pygame

import time
import pygame

#音乐路径
filePath = r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\7、播放音乐\res\0.mp3"


# 初始化
pygame.mixer.init()

#加载音乐
track = pygame.mixer.music.load(filePath)

#播放
pygame.mixer.music.play()

#
time.sleep(5)
pygame.mixer.music.pause()#暂停
#停止
pygame.mixer.music.stop()


04修改背景图片

# win键加R   ->regedit ->HKEY_CURRENT_USER->
#Control panel->Desktop->

import win32api
import win32con
import win32gui

def setWallPaper(path):
    #打开注册表
    reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
             "Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    #2拉伸 0居中 6适应 10填充
    win32api.RegSetValueEx(reg_key,"WallpaperStyle",0,win32con.REG_SZ,"6")

    #
    # win32api.RegSetValueEx(reg_key,)
    # win32api.RegSetValueEx(reg_key,"WallPaper" )
    # win32con.SPIF_SENDWININICHANGE立即生效
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,path,
                                  win32con.SPIF_SENDWININICHANGE)


# 图片地址
setWallPaper(r"")

05整蛊程序

import time
import pygame
import win32api
import win32con
import win32gui
import threading

def go():
    pygame.mixer.init()
    while 1:
        for i in range(5):
            filePath =\
                r"H:\QIANfeng code\17自动化办公鼠标键盘模拟\res"+"\\"+str(i)+".mp3"
            track = pygame.mixer.music.load(filePath)
            pygame.mixer.music.play()
            time.sleep(10)
            pygame.mixer.music.stop()


def setWallPaper(path):
    reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
             "Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
    win32api.RegSetValueEx(reg_key,"WallpaperStyle",0,win32con.REG_SZ,"6")

    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,path,
                                  win32con.SPIF_SENDWININICHANGE)
#线程
th = threading.Thread(target = go ,name ="LoopThread")
th.start()
while True:
    go()
    for i in range(9):
        filePath = r"H:\QIANfeng code\17自动化办公鼠标键盘模拟\res1"+"\\"+str(i)+".jpeg"
        print(filePath)
        setWallPaper(filePath)
        time.sleep(5)

06键盘模拟

import win32con
import win32api
import time


'''
win32api.keybd_event(91,0,0,0)
time.sleep(0.1)
win32api.keybd_event(91,0,win32con.KEYEVENTF_KEYUP,0)
'''
while 1 :
    win32api.keybd_event(91,0,0,0)
    time.sleep(0.1)
    win32api.keybd_event(77,0,0,0)
    time.sleep(0.1)
    win32api.keybd_event(77,0,win32con.KEYEVENTF_KEYUP,0)
    win32api.keybd_event(91, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(3)

07语音控制游戏

08鼠标模拟

import win32con
import win32api
import time


win32api.SetCursorPos([30,40])
time.sleep(0.1)
#鼠标左键按下
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0)
#鼠标左键抬起 
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0)

win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0)





09读取doc与docx文件

import win32com
import win32com.client


def readWordFile(path):
    #调用系统word功能,可以处理doc和 docx两种文件
    mw = win32com.client.Dispatch("Word.Application")
    #打开文件
    doc = mw.Documents.Open(path)
    for paragraph in doc.Paragraphs:
        line = paragraph.Range.Text
        print(line)
    #关闭文件
    doc.Close()
    #退出文件
    mw.Quit()





path = r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\4、word自动化办公\sunck.doc"
readWordFile(path)



10读取doc与docx文件并写入其他文件

import win32com
import win32com.client


def readWordFile(path):
    mw = win32com.client.Dispatch("Word.Application")
    doc = mw.Documents.Open(path)

    #将word的数据保存到另一个文件
    doc.SaveAs(toPath,2)#2表示txt文件


    doc.Close()
    mw.Quit()

toPath = r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\4、word自动化办公\1.txt"










11创建word文件

import win32com
import win32com.client
import os


def makeWordFile(path,name):
    word = win32com.client.Dispatch("Word.Application")
    #创建文档
    doc = word.Documents.Add()
    #文档可见
    word.Visible = True
    #写内容
    #从头开始写
    r = doc.Range(0,0)
    r.InsertAfter("亲爱的"+name+"\n")
    r.InsertAfter("想你")
    #存储文件
    doc.SaveAs(path)
    #关闭文件
    doc.Close()
    #退出文件
    # word.Quit()


names = ["zhangsan","lisi","wangwu"]
for name in names:
    path = os.path.join(os.getcwd(),name)
    makeWordFile(path,name)

path = r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\4、word自动化办公"

12读取xlsx文件

#xlsx xls
#openpyxl->xlsx

from openpyxl.reader.excel import load_workbook


def readXlsxFile(path):
    file= load_workbook(filename = path)
    print(file.get_sheet_names())
    sheets = file.get_sheet_names()
    #拿出一个表格
    sheet = file.get_sheet_by_name(sheets[0])
    #最大行数
    print(sheet.max_row)
    #最大列数
    print(sheet.max_column)
    #表名
    print(sheet.title)

    for lineNum in range(1,sheet.max_row+1):
        print(lineNum)
        lineList = []
        for columnNum in range(1,sheet.max_column):
            #拿数据
            value = sheet.cell(row=lineNum,column = columnNum).value
            # if value!=None:
            lineList.append(value)

        print(lineList)



path= r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\5、excel自动化办公\1.xlsx"
readXlsxFile(path)






13返回整体xlsx数据

#  xlsx   xls
# openpyxl  ->  xlsx

from openpyxl.reader.excel import load_workbook

def readXlsxFile(path):
    dic = {}
    file = load_workbook(filename=path)
    sheets = file.get_sheet_names()
    print(len(sheets))

    for sheetName in sheets:
        sheet = file.get_sheet_by_name(sheetName)
        #一张表的所有数据
        sheetInfo = []
        for lineNum in range(1, sheet.max_row + 1):
            lineList = []
            for columnNum in range(1, sheet.max_column + 1):
                value = sheet.cell(row=lineNum, column=columnNum).value
                lineList.append(value)
            sheetInfo.append(lineList)

        #将一张表的数据存到字典
        dic[sheetName] = sheetInfo
    return dic

#不能处理xls文件
path = r""
dic = readXlsxFile(path)
print(dic["安力博发"])
print(len(dic))





14返回xls和xlsx文件内容

#有序字典
from collections import OrderedDict
#读取数据
from pyexcel_xls import get_data

def readXlsAndXlsxFile(path):
    dic = OrderedDict()

    #抓取数据
    xdata = get_data(path)
    for sheet in xdata:
        dic[sheet]= xdata[sheet]
    return dic



path= r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\5、excel自动化办公\1.xlsx"
dic = readXlsAndXlsxFile(path)
print(dic)
print(len(dic))

15写入xls文件

#有序字典
from collections import OrderedDict
#读取数据
from pyexcel_xls import get_data
from pyexcel_xls import save_data



def makeExcelFile(path,data):
    dic = OrderedDict()
    for sheetName,sheetValue in data.items():
        d= {}
        d[sheetName]=sheetValue
        dic.update(d)

    save_data(path,dic)







#只能写xls
path= r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\5、excel自动化办公\11.xls"
makeExcelFile(path,{"表1":[[1,2,3],[4,5,6]],
                    "表2":[[11,22,33],[44,55,66]]
                    })



16写ppt

import win32com
import win32com.client


def makeppt(path):
    ppt = win32com.client.Dispatch("PowerPoint.Application")
    ppt.Visible=True

    #增加一个文件
    pptFile = ppt.Presentations.Add()

    #创建页  参数1为页数 参数2为主题类型
    page1 = pptFile.Slides.Add(1,1)

    #正标题副标题 就两个
    t1 = page1.Shapes[0].TextFrame.TextRange
    t1.Text = "Liuwang "
    t2 = page1.Shapes[1].TextFrame.TextRange
    t2.Text = "Liuwang is a good man  "

    # 第二页
    page2 = pptFile.Slides.Add(2, 2)
    t3 = page2.Shapes[0].TextFrame.TextRange
    t3.Text = "LiuGE "
    t4 = page2.Shapes[1].TextFrame.TextRange
    t4.Text = "LiuGE is a good man  "
    #保存
    pptFile.SaveAs(path)
    pptFile.Close()
    ppt.Quit()





path = r"D:\xiazaipan\第1章  Python语言基础\15、自动化办公与鼠标键盘模拟\4、word自动化办公"
makeppt(path)

猜你喜欢

转载自blog.csdn.net/qq_41856814/article/details/89416387