一、Python 處理Excel
Python 實現對excel 文件的讀寫功能主要有三個模塊:xlwt 、xlrd 和openpyxl 。
這裏用openpyxl
模塊。 Python 沒有自帶openpyxl ,所以必須安裝。openpyxl 只能操作xlsx 文件而不能操作xls 文件。
三個重要概念:
Workbook 是一個打開的excel 文件,即excel 工作簿;Sheet 是工作簿中的一張表,即工作表;
Cell 就是一個單元格 。
注意:光理論是不夠的,在此送大家一套2020最新Python全棧實戰視頻教程,點擊此處 進來獲取 跟着練習下,希望大家一起進步哦!
操作步驟:
打開Workbook ,定位Sheet ,操作Cell。
代碼:
import openpyxl # 導入模塊
wb = openpyxl.load_workbook('學生信息.xlsx') # 加載Excel表格
wb.sheetnames # 取得工作簿中所有表名的列表
wb.active #當前活動表格
sheet = wb.worksheets[0] # 獲取第一張表格
sheet = wb['Sheet1']# 獲取Sheet1表格
sheet.title # 表格的名字
cell=sheet['A1'] # 一個單元格
cell=sheet.cell(row=1, column=1)# 一個單元格
cell.row # 單元格的行號
cell.column # 單元格的列號
cell.value # 單元格的值
sheet['A1'].value = 'Hello' # 給單元格的附值
sheet.cell(row=1, column=2).value = 30 # 給單元格的附值
sheet['A1'].value # 單元格的值
sheet.cell(row=1, column=1).value # 單元格的值
sheet['A1':'C3'] # 獲取多個單元格
openpyxl.utils.get_column_letter(2) # B 列字母和數字之間的轉換
openpyxl.utils.column_index_from_string("B") # 2
wb = openpyxl.Workbook() # 創建一個空的Excel 文檔
wb.save('學生信息.xlsx') # 打開或者創建Excel後都要保存
sheet=wb.create_sheet(index=0, title='First') # 創建一個表格sheet
del wb['Sheet1'] # 刪除Sheet1表格
wb.remove(wb['Sheet1']) # 刪除Sheet1表格
sheet['A3'] = '=SUM(A1:A2)' # 使用加法公式
sheet.row_dimensions[1].height = 10 # 設置第一行的行高爲10
sheet.column_dimensions['B'].width = 20 # 設置第一列的寬度爲20
sheet.merge_cells('A1:D3') # 合併A1~D3的單元格
sheet.unmerge_cells('A1:D3')# 拆分A1~D3的單元格
舉例:生成圖表
import openpyxl
from openpyxl.chart import BarChart, Series, Reference
wb=openpyxl.load_workbook("工資統計.xlsx")
sheet=wb["工作量彙總"]
result=openpyxl.Workbook()
result.create_sheet(index=0,title="工資圖表")
test=result["工資圖表"]
maxrow=sheet.max_row
test.cell(row=1, column=1).value = sheet.cell(row=1, column=2).value
test.cell(row=1, column=2).value = sheet.cell(row=1, column=6).value
for i in range(2,maxrow+1):
test.cell(row=i,column=1).value=sheet.cell(row=i,column=2).value
test.cell(row=i, column=2).value = float(sheet.cell(row=i, column=6).value)
chart1 = BarChart()
chart1.type = "col"
chart1.style = 10
chart1.title = "工資圖表"
chart1.y_axis.title = '工資'
chart1.x_axis.title = '姓名'
data = Reference(test, min_col=2, max_col=2,min_row=1, max_row=maxrow) # 條形圖中的數字數據(看見的矩形)
cats = Reference(test, min_col=1, min_row=2, max_row=maxrow) # 橫座標上的姓名
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
test.add_chart(chart1, "A10")
wb.save("工資統計.xlsx")
result.save("工資表.xlsx")
二、Python 處理 Word
Word 文檔和PDF 是二進制文件,所以它們比純文本文件要複雜得多,因爲除了文本之外,它們還保存了許多字體、顏色和佈局信息 。
import docx
三個概念:
Document
對象表示整個文檔,是最高層。
Document 對象包含一個Paragraph
對象的列表,表示文檔中的段落。
每個Paragraph 對象都包含一個Run
對象的列表。
一個Run對象就是一種樣式!一個Run 對象是相同樣式文本的延續。
代碼:
import docx # 加載模塊
doc = docx.Document('實驗報告.docx') # 加載文檔
len(doc.paragraphs) # 文章段落個數
doc.paragraphs[1].text # 第2段文字
doc.paragraphs[1].runs[0].text # 第1段的第1個樣式的文字
doc = docx.Document() # 創建一個新的Word文檔
para=doc.add_paragraph('Hello world!') # 添加一個段落
para.add_run(' secondparagraph.') # 已有段落的末尾添加文本
doc.save('實驗報告.docx') # 保存文檔
doc.add_heading('Header 0', level=0) # 添加標題
run1.font.color.rgb = RGBColor(0,0,0) # 設置Run對象的顏色
run1.font.size = Pt(20) # 設置rund對象字體大小
run.add_break() # 添加換行符,注意是Run對象調用
doc.add_page_break() # 添加換頁符,注意是doc對象調用
doc.add_picture('gird.png',width=docx.shared.Inches(1),height=docx.shared.Cm(4)) # 添加圖像
table = doc.add_table(rows=2, cols=2, style='Table Grid') # 添加表格
cell = table.cell(0, 0)
table.cell(0, 1).text = 'world'
row = table.rows[1] # 獲得表格1行
row.cells[0].text = 'world' 第一行第0個單元格的值
row = table.add_row() # 增加一行
實例:將Excel表格轉換爲Word表格
import docx
import openpyxl
import random
from docx.oxml.ns import qn
from docx.shared import Pt, RGBColor
wb=openpyxl.load_workbook("工資統計.xlsx")
sheet=wb["工作量彙總"]
doc=docx.Document()
maxrow=sheet.max_row
maxcol=sheet.max_column
table=doc.add_table(rows=maxrow,cols=maxcol)
for i in range(maxrow):
for j in range(maxcol):
run = table.cell(i,j).paragraphs[0].add_run(str(sheet.cell(i+1,j+1).value))
run.font.color.rgb = RGBColor(int(random.random() * 255), int(random.random() * 255), int(random.random() * 255))
wb.save("工資統計.xlsx")
doc.save("工資統計.docx")
三、Python 處理 PDF
import PyPDF2
PyPDF2 不能從PDF 文檔中提取圖像、圖表或其它媒體,但它可以提取文本,並將文本返回爲Python 字符串 。
import PyPDF2
file = open('實驗.pdf', 'rb') # 'rb' 讀打開pdf文檔
reader = PyPDF2.PdfFileReader(file) # 讀pdf對象
reader.numPages # 返回文檔頁數
page = reader.getPage(0) # 獲得reader的第一頁
在PyPDF2 中,與PdfFileReader 對象相對的是PdfFileWriter 對象,不能將任意文本寫入PDF ,僅限於從其它PDF 中拷貝頁面、旋轉頁面、重疊頁面和加密文件 。
模塊 不允許直接編輯PDF ,必須創建一個新的PDF ,然後從已有的文檔拷貝內容 。
步驟如下:
- 打開一個或多個已有的PDF ,得到PdfFileReader 對象。
- 創建一個新的PdfFileWriter對象。
- 將頁面從PdfFileReader 對象拷貝到PdfFileWriter 對象中。
- 最後,利用 PdfFileWriter 對象寫入輸出的PDF 。
合併文件:
addPage() 添加頁面,在末尾。
import PyPDF2
import os
pdf_output=PyPDF2.PdfFileWriter()
filter=[".pdf"]
for root, dirs, files in os.walk("C:/Users/自由自在/PycharmProjects/文件操作"):
for filespath in files:
name=os.path.join(root,filespath)
ext=os.path.splitext(name)[1]
if ext in filter:
file = open(filespath, "rb")
reader = PyPDF2.PdfFileReader(file)
print(reader.isEncrypted)
if not reader.isEncrypted:
for i in range(reader.getNumPages()):
page = reader.getPage(i)
pdf_output.addPage(page)
file.close()
with open("result.pdf","wb") as file1:
pdf_output.write(file1)
加密,解密PDF文件:
import PyPDF2
reader = PyPDF2.PdfFileReader(open('加密.pdf', 'rb'))
writer = PyPDF2.PdfFileWriter()
for num in range(reader.numPages):
writer.addPage(reader.getPage(num))
writer.encrypt('mima:hello') # 加密,傳入口令字符串
with open('加密後.pdf', 'wb') as f:
writer.write(f)
reader.isEncrypted # 判斷是否加密
reader.decrypt('mima:hello') # 解密
旋轉頁面:
利用rotateClockwise()
和rotateCounterClockwise()
方法,PDF 文檔的頁面也可以旋轉90 度的整數倍。
Word 文件轉換爲PDF 文件:
import glob
import re
from win32com import client as wc
word = wc.Dispatch('Word.Application')
# glob.glob 遍歷指定目錄下的所有文件和文件夾,不遞歸遍歷
files = glob.glob('F:/*.docx')
for file in files:
name = re.findall('(.*).docx', file)[0]
try:
doc = word.Documents.Open(file)
doc.SaveAs('%s.pdf' % name, 17) # wdFormatPDF = 17
doc.Close()
except:
continue
word.Quit()
添加水印:
import PyPDF2
pdf_output=PyPDF2.PdfFileWriter()
file=open('meeting.pdf', 'rb')
filemark=open("watermark.pdf","rb")
pdf_input=PyPDF2.PdfFileReader(file)
pdf_watermark=PyPDF2.PdfFileReader(filemark)
for i in range(pdf_input.getNumPages()):
page=pdf_input.getPage(i)
page.mergePage(pdf_watermark.getPage(0))
pdf_output.addPage(page)
with open('meeting11111.pdf',"wb") as file3:
pdf_output.write(file3)
file.close()
filemark.close()
注意:最後送大家一套2020最新企業Pyhon項目實戰視頻教程,點擊此處 進來獲取 跟着練習下,希望大家一起進步哦!
總有一句會讓你找到努力的理由!
希望我們都能用最少的悔恨面對過去,用最少的浪費面對現在,用最多的夢面對未來。加油~