99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀聊聊python辦公自動化之Word(上)
聊聊python辦公自動化之Word(上)
2020-11-25
收藏

作者:星安果

來源:公眾號AirPython

日常自動化辦公中,使用python真的能做到事半功倍!在上一個系列中,我們對python操作Excel進(jìn)行了一次全面總結(jié)。從本篇文章開始,我們繼續(xù)聊聊另外一種常見的文檔格式:Word。

準(zhǔn)備

Python 操作 Word 最常見的依賴庫是:python-docx。所以,在開始操作之前,我們需要在虛擬環(huán)境下安裝這個依賴庫。

# 安裝依賴
pip3 install python-docx

寫入實戰(zhàn)

我們需要了解一個 Word 文檔的頁面結(jié)構(gòu),它們分別是:

  • 文檔 - Document
  • 章節(jié) - Section
  • 段落 - Paragraph
  • 文字塊 - Run

經(jīng)常操作的數(shù)據(jù)類型包含:段落、標(biāo)題、列表、圖片、表格、樣式。首先,使用 Document 創(chuàng)建一個文檔對象,相當(dāng)于創(chuàng)建一個空白文檔。

from docx import Document

# 1、新建一個空白文檔
doc = Document()

然后,就可以往文檔中寫入數(shù)據(jù)了。使用文檔對象的 add_heading(text,level) 方法可以寫入標(biāo)題。其中,第 1 個參數(shù)為標(biāo)題內(nèi)容,第 2 個參數(shù)代表標(biāo)題的級別,比如:分別寫入一級標(biāo)題、二級標(biāo)題、三級標(biāo)題。

# 2、新增內(nèi)容
# 2.1 標(biāo)題
# 分別寫入一個一級標(biāo)題,一個二級標(biāo)題,一個三級標(biāo)題
doc.add_heading('一級標(biāo)題', 0)
doc.add_heading('二級標(biāo)題', 1)
doc.add_heading('三級標(biāo)題', 2)

段落 Paragraph 包含 3 類,分別是:

  • 普通段落
  • 自定義樣式的段落
  • 引用段落

默認(rèn)情況下,使用文檔對象的 add_paragraph(text,style) 方法來添加一個段落。

普通段落:假如第二個參數(shù) style 沒有傳入,則代表添加一個普通的段落。

引用段落:對于引用段落,只需要指定段落樣式為 Intense Quote 即可。

# 2.2.1 新增普通段落
doc.add_paragraph("我是一個普通段落。")

# 2.2.3 新增一個引用段落
# 只需要指定樣式為:Intense Quote
doc.add_paragraph('--我是一個引用段落--', style='Intense Quote')

自定義樣式的段落:這里有 2 種實現(xiàn)方式分別是:

  • 創(chuàng)建一個空的段落對象,增加文字塊 Run 的時候,同時指定字體樣式;
  • 使用文檔對象創(chuàng)建一個新的樣式(或已經(jīng)存在的樣式),然后添加段落的時候,設(shè)置到第二個參數(shù)中。

考慮到樣式的樣式的復(fù)用性,第 2 種方式可能更實用,對應(yīng)的方法是:

document.styles.add_style(style_name,type) 

以第 2 種實現(xiàn)方式為例,新增一個自定義樣式的段落,設(shè)置段落的字體名稱、大小、顏色、是否加粗、對齊方式等。

PS:第 1 種實現(xiàn)方式,文末源碼會提供。

該方法第 2 個參數(shù)用來指定樣式類型,包含 3 種。

分別對應(yīng)關(guān)系如下:

  • 1:段落樣式
  • 2:字符樣式
  • 3:表格樣式
def create_style(document, style_name, style_type, font_size=-1, 
                 font_color=None, font_name=None, align=None):
    """
    創(chuàng)建一個樣式
    :param align:
    :param document:
    :param style_name: 樣式名稱
    :param style_type: 樣式類型,1:段落樣式, 2:字符樣式, 3:表格樣式
    :param font_name:
    :param font_color:
    :param font_size:
    :return:
    """
    if font_color is None: font_color = []

    # 注意:必須要判斷樣式是否存在,否則重新添加會報錯
    style_names = [style.name for style in document.styles]
    if style_name in style_names:
        # print('樣式已經(jīng)存在,不需要重新添加!')
        return

    font_style = document.styles.add_style(style_name, style_type)

    # 字體大小
    if font_size != -1:
        font_style.font.size = Pt(font_size)

    # 字體顏色
    # 比如:[0xff,0x00,0x00]
    if font_color and len(font_color) == 3:
        font_style.font.color.rgb = RGBColor(font_color[0], font_color[1], font_color[2])

    # 對齊方式
    # 注意:段落、表格才有對齊方式
    if style_type != 2 and align:
        font_style.paragraph_format.alignment = align
        # font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        # font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
        # font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT

    # 中文字體名稱
    if font_name:
        font_style.font.name = font_name
        font_style._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)

    return font_style

需要注意的是,新添加的樣式的時候,必須先判斷樣式名稱是否存在,否則會報錯。最后,添加段落的時候,將上面創(chuàng)建的樣式傳入到第 2 個參數(shù)中即可。

使用 add_paragraph() 方法添加一個段落,返回值為一個段落對象
該對象同樣可以使用 add_run(text,style) 方法,在段落后追加文字塊 Run 并指定樣式
# 1/段落樣式
style_paragraph = create_style(document=doc, style_name="style2", style_type=1, font_size=30,
                               font_color=[0xff, 0x00, 0x00])
# 2/字符樣式
style_string = create_style(document=doc, style_name="style3", style_type=2, font_size=15,
                            font_color=[0x00, 0xff, 0x00])
# 3/表格樣式
# 對齊方式為:居中
style_table = create_style(document=doc, style_name="style4", style_type=3, font_size=25,
                           font_color=[0x00, 0x00, 0xff], align=WD_PARAGRAPH_ALIGNMENT.CENTER)

current_paragraph = doc.add_paragraph("我是一個自帶樣式的段落(方式二)?。?!", style_paragraph)
# 字符樣式

current_paragraph.add_run("【段落2中的部分字符】", style_string)
Word 文檔中,有序列表和無序列表也比較常用
事實上,和添加段落類似,添加列表同樣是使用文檔對象的 add_paragraph() 方法,
指定不同的樣式 style 來添加
其中,
有序列表:List Number
無序列表:List Bullet
def add_list(document, data, isorder):
    """
    將列表數(shù)據(jù)添加到無序列表/有序列表中
    :param document: 文檔對象
    :param data: 列表數(shù)據(jù)
    :param isorder: 是否有序列表
    :return:
    """
    # 無序列表
    if not isorder:
        for item in data:
            document.add_paragraph(item, style='List Bullet')
    else:
        # 有序列表
        for item in data:
            document.add_paragraph(item, style='List Number')

# 2.3 列表
# 2.3.1 無序列表
add_list(doc, ["無序-Item1", "無序-Item2", "無序-Item3"], False)

# 2.3.2 有序列表
add_list(doc, ["有序-Item1", "有序-Item2", "有序-Item3"], True)

接下來,我們看看如何在文檔中插入圖片,使用方法:

add_picture(image,widht,height)

其中,

  • 第 1 個參數(shù)代表圖片路徑或者圖片流(網(wǎng)絡(luò)圖片)
  • 第 2、3 個參數(shù)用于設(shè)置圖片的寬、高

需要注意的是,如果沒有顯式指定寬高,則以圖片原生尺寸展示;如果僅設(shè)置了其中一個,則會按照設(shè)置的一個做等比縮放顯示。寫入本地圖片很簡單。

def add_local_image(doc, image_path, width=None, height=None):
    """
    增加本地圖片到Word文檔中
    :param doc:
    :param image_path:
    :param width:
    :param height:
    :return:
    """
    doc.add_picture(image_path, width=None if width is None else Inches(width),
                    height=None if height is None else Inches(height))

# 2.4.1 插入本地圖片
add_local_image(doc, './1.png', width=2)

對于網(wǎng)絡(luò)圖片,我們需要先通過網(wǎng)絡(luò)圖片地址,獲取圖片字節(jié)流,傳入到第一個參數(shù)中即可。

import ssl
from io import BytesIO

def get_image_data_from_network(url):
    """
    獲取網(wǎng)絡(luò)圖片字節(jié)流
    :param url: 圖片地址
    :return:
    """
    ssl._create_default_https_context = ssl._create_unverified_context
    # 獲取網(wǎng)絡(luò)圖片的字節(jié)流
    image_data = BytesIO(urlopen(url).read())
    return image_data

def add_network_image(doc, image_url, width=None, height=None):
    """
    增加本地圖片到Word文檔中
    :param doc:
    :param image_url:
    :param width:
    :param height:
    :return:
    """
    # 獲取圖片流
    image_data = get_image_data_from_network(image_url)
    doc.add_picture(image_data, width=None if width is None else Inches(width),
                    height=None if height is None else Inches(height))

# 2.4.2 插入網(wǎng)絡(luò)圖片
url = '圖片URL地址'
add_network_image(doc, url, width=3)

最后,我們看看如何在文檔中插入表格。使用方法:

add_table(row_num,column_num,style=None)

返回值:表格對象 

其中,

  • 第 1 個參數(shù):表格的行數(shù)目
  • 第 2 個參數(shù):表格的列數(shù)目
  • 第 3 個參數(shù):表格的樣式

使用行/列索引,可以獲取表格中某一行/列所有的單元格對象組成的列表。

# 添加一個table表格
table = doc.add_table(***)

# 通過行/列索引,獲取某一行/列的所有單元格對象
# 第一行所有單元格對象列表
head_cells = table.rows[0].cells

另外,表格對象使用 add_row()、add_column() 方法可以追加一行/列,以指定表頭、表數(shù)據(jù),插入一張表為例。

def add_table(doc, head_datas, datas, style=None):
    """
    新增一個表格
    :param doc:
    :param head_datas: 表頭
    :param datas: 數(shù)據(jù)
    :param style:
    :return:
    """
    # 新增一個表格
    # 表格所有樣式大全:https://blog.csdn.net/ibiao/article/details/78595295
    # 默認(rèn)樣式為:Table Grid
    table = doc.add_table(rows=1, cols=len(head_datas), 
                          style=("Table Grid" if style is None else style))

    # 第一行所有單元格對象列表
    head_cells = table.rows[0].cells

    # 寫入數(shù)據(jù)到表頭中
    for index, head_item in enumerate(head_datas):
        head_cells[index].text = head_item

    # 遍歷數(shù)據(jù)并寫入數(shù)據(jù)
    for data in datas:
        # 單獨添加一行或者列:add_row、add_column
        row_cells = table.add_row().cells
        for index, cell in enumerate(row_cells):
            cell.text = str(data[index])
# 2.5 表格
head_datas = ["姓名", "年齡", "地區(qū)"]
datas = (
  ('張三', 18, '深圳'),
  ('李四', 28, '北京'),
  ('王五', 33, '上海'),
  ('孫六', 42, '廣州')
 )

# 新增一個表格,并指定樣式
# add_table(doc, head_datas, datas, style_table)
add_table(doc, head_datas, datas)

需要指出的是,表格默認(rèn)采用的樣式是 Table Grid,也可以使用上面的方法自定義一個表格樣式,插入表格的同時設(shè)置進(jìn)去即可。

最后

本篇文章就 Word 寫入數(shù)據(jù)的常規(guī)操作進(jìn)行了一次全面梳理,更多功能包含:讀取、修改、查找、刪除等實戰(zhàn)內(nèi)容后面會持續(xù)輸出。



——熱門課程推薦:

想學(xué)習(xí)PYTHON數(shù)據(jù)分析與金融數(shù)字化轉(zhuǎn)型精英訓(xùn)練營,您可以點擊>>>“人才轉(zhuǎn)型”了解課程詳情;

想從事業(yè)務(wù)型數(shù)據(jù)分析師,您可以點擊>>>“數(shù)據(jù)分析師”了解課程詳情;

想從事大數(shù)據(jù)分析師,您可以點擊>>>“大數(shù)據(jù)就業(yè)”了解課程詳情;

想成為人工智能工程師,您可以點擊>>>“人工智能就業(yè)”了解課程詳情;

想了解Python數(shù)據(jù)分析,您可以點擊>>>“Python數(shù)據(jù)分析師”了解課程詳情;

想咨詢互聯(lián)網(wǎng)運營,你可以點擊>>>“互聯(lián)網(wǎng)運營就業(yè)班”了解課程詳情; 

想了解更多優(yōu)質(zhì)課程,請點擊>>>


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }