Python在平時寫寫小工具真是方便快捷,Pyhon大法好。
以下所有代碼都是找了好多網上的大佬分享的代碼按照自己的需求改的。
調用的庫為Python-docx、win32com、PyPDF2、xlwings(操作excel)
因為公司的任務要對上千個word文件進行批量操作,手工操作太累了,于是加班加點趕出來了一個自動化腳本,雖然還有很多要優化的地方,但已經可以穩定運行了。下面記錄一下腳本功能。
1.doc轉docx
因為Python-docx庫只能對docx文件操作,所以要轉格式,直接改后綴不行。
word = wc.Dispatch("Word.Application")
# 不能用相對路徑,老老實實用絕對路徑
# 需要處理的文件所在文件夾目錄
for root, dirs, files in os.walk(rawpath):
for i in files:
# 找出文件中以.doc結尾并且不以~$開頭的文件(~$是為了排除臨時文件的)
if i.endswith('.doc') and not i.startswith('~$'):
print(i)
doc = word.Documents.Open(root +'\\'+ i)
# # 將文件名與后綴分割
rename = os.path.splitext(i)
# 將文件另存為.docx
doc.SaveAs(root + '\\' +rename[0] + '.docx', 12) # 12表示docx格式
doc.Close()
# time.sleep(1)
word.Quit()
2.找到特定文件
這個比較簡單,只需要循環遍歷文件夾,按照隊列里的關鍵字將目標文件添加的隊列里即可。
因為轉pdf只能是docx,所以要找docx文件,同時過濾~$文件開頭的臨時文件。
def findfiles():
count = 1
for root, dirs, files in os.walk(path):
for filename in files:
for i in range(len(filenames)):
if (filenames[i] in filename and filename.endswith('docx') and not filename.startswith('~$') :
result.append([count, root + "\\" + filename])
count += 1
break
print(result)
3.所有字體顏色變為黑色
def change_color(path):
file = Document(path)
for pag in file.paragraphs:
for block in pag.runs:
block.font.color.rgb = RGBColor(0, 0, 0)
for table in file.tables:
for row in table.rows:
for cell in row.cells:
for cell_pag in cell.paragraphs:
for cell_block in cell_pag.runs:
cell_block.font.color.rgb = RGBColor(0, 0, 0)
# 頁眉
pag_head = file.sections[0].header
head_pag = pag_head.paragraphs[0]
for run in head_pag.runs:
run.font.color.rgb = RGBColor(0, 0, 0)
# 頁腳
pag_foot = file.sections[0].footer
foot_pag = pag_foot.paragraphs[0]
for run in foot_pag.runs:
run.font.color.rgb = RGBColor(0, 0, 0)
file.save(path)
print(path)
print("^"*10 + "顏色切換完成" + "^"*10)
4.docx轉pdf
因為分頁操作只能pdf實現。
for i in range(len(result)):
file = result[i][1]
name = file.rsplit('\\', 1)[1]
print(i)
if "關鍵字" in name: # 跳過不需要截取的關鍵字文件
outfile = pdf_file_path + name[:-5] + str(i) +'.pdf'
else:
outfile = out_path + name[:-5] + str(i) +'.pdf'
if file.split(".")[-1] == 'docx':
print(file)
convert(file, outfile)
print("^"*10+"PDF轉換完成"+"^"*10)
time.sleep(1)
5.截取特定頁面
def split_single_pdf(read_file, start_page, end_page, pdf_file):
# 1. 獲取原始pdf文件
fp_read_file = open(read_file, 'rb')
# 2. 將要分割的PDF內容格式化
pdf_input = PdfFileReader(fp_read_file)
# 3. 實例一個 PDF文件編寫器
pdf_output = PdfFileWriter()
# 4. 把第一頁放到PDF文件編寫器
for i in range(start_page, end_page):
pdf_output.addPage(pdf_input.getPage(i))
# 5. PDF文件輸出
with open(pdf_file, 'wb') as pdf_out:
pdf_output.write(pdf_out)
print(f'{read_file}分割{start_page}頁-{end_page}頁完成,保存為{pdf_file}!')
6.調用打印機打印
def printer_loading(filename):
win32api.ShellExecute(0, "print", filename, '/d:"%s"' % win32print.GetDefaultPrinter(), ".", 0)
7.對execl特定頁面打印
def excel_print(execl_path):
app = xw.App(visible=False, add_book=False)
workbook = app.books.open(execl_path)
worksheet = workbook.sheets['sheet關鍵字']
area = worksheet.range('A1:D11') # 打印區域
area.api.PrintOut(Copies=1, ActivePrinter='Canon MF260 Series UFRII LT', Collate=True)
workbook.close()
app.quit()
本文內容不用于商業目的,如涉及知識產權問題,請權利人聯系51Testing小編(021-64471599-8017),我們將立即處理