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

熱線電話:13121318867

登錄
首頁大數(shù)據(jù)時(shí)代聊聊python 辦公自動(dòng)化之 Excel(下)
聊聊python 辦公自動(dòng)化之 Excel(下)
2020-11-06
收藏

作者:星安果

來源:AirPython

前面談到python 處理 Excel 文件最常見的兩種方式,即:xlrd/xlwt、openpyxl。其中,xlrd/xlwt 這一組合,xlrd 可以負(fù)責(zé)讀取數(shù)據(jù),而 xlwt 則負(fù)責(zé)寫入數(shù)據(jù),缺點(diǎn)是不支持 xlsx。openpyxl 同時(shí)支持對 Excel 文檔的讀取、寫入操作,缺點(diǎn)是不支持 xls。本篇文章將繼續(xù)聊聊python 操作 Excel 文檔的其他幾種方式。

xlsxwriter

xlsxwriter 主要用于將數(shù)據(jù)、圖表寫入到 Excel 文件中,可以配置使用較小的內(nèi)存快速寫入數(shù)據(jù)。

它的缺點(diǎn)是:無法讀取、修改已有的 Excel 文件;如果需要讀取修改 Excel 文件,只能搭配其他依賴庫使用,比如:xlrd。

首先安裝 xlsxwriter 的依賴包:

# 安裝依賴包
pip3 install xlsxwriter

xlsxwriter 提供了 Workbook(filename) 方法,用于創(chuàng)建一個(gè)工作簿對象。使用工作簿對象的 add_worksheet(sheet_name) 函數(shù),就可以在工作簿中創(chuàng)建 Sheet 了。

def create_workbook_and_worksheet(filename, worksheet_names):
    """
    創(chuàng)建工作簿和Sheet
    :param filename: 文件名稱
    :param worksheet_names: sheet名稱列表
    :return:
    """
    wb = xlsxwriter.Workbook(filename)

    sheets = []

    # 新增sheet
    for worksheet_name in worksheet_names:
        sheets.append(wb.add_worksheet(worksheet_name))

    return wb, sheets

接著,就可以往某個(gè) Sheet 單元格中寫入數(shù)據(jù)了。如果需要定制單元格的樣式,比如:字體大小、字體、顏色、背景、是否加粗等,可以使用工作簿對象的 add_format() 方法創(chuàng)建一個(gè)樣式。

def create_format_styles(wb, format_stuyles):
    """
    創(chuàng)建一個(gè)樣式,包含:字體大小、字體、顏色、背景、是否加粗等
    :param wb:
    :param format_stuyles:
    :return:
    """
    return wb.add_format(format_stuyles)

# 單元格字體樣式
self.title_style = {'bold': True, 'bg_color': '#B0C4DE', 'font_size': 10,'font_name': 'Microsoft yahei'}

# 創(chuàng)建標(biāo)題字體樣式
title_font_style = create_format_styles(self.wb, self.title_style)

Sheet 對象的 write(...) 函數(shù)用于向單元格中寫入數(shù)據(jù),參數(shù)包含:行索引、列索引、值、字體樣式等。需要注意的是,默認(rèn) xlsxwriter 的行索引、列索引都是從 0 開始,即: 0 代表第一行。

寫入數(shù)據(jù)的同時(shí)配置單元格樣式的寫法如下:

def write_to_cell(sheet, row_index, column_index, value, format_styles=None):
    """
    往單元格中寫入數(shù)據(jù)
    :param row_index: 行索引,1:第一行
    :param column_index: 列索引,1:第一列
    :param format_styles 字體樣式
    :return:
    """
    if row_index < 1 or column_index < 1:
        print('參數(shù)輸入不正確,寫入失?。?)
    else:
        # 注意:默認(rèn)xlsxwriter的行索引、列索引從0開始
        sheet.write(row_index - 1, column_index - 1, value, format_styles)

# 往worksheet中寫入數(shù)據(jù)
# 第一行
write_to_cell(self.current_sheet, 1, 1, "姓名", title_font_style)
write_to_cell(self.current_sheet, 1, 2, "年齡", title_font_style)
# 第二行
write_to_cell(self.current_sheet, 2, 1, 'xingag')
write_to_cell(self.current_sheet, 2, 2, 23)

xlsxwriter 同樣支持在單元格中插入圖片,包含:本地圖片和網(wǎng)絡(luò)圖片。

使用的方法是:insert_image();

參數(shù)包含:單元格行索引索引從 0 開始)、單元格列索引、圖片文件、可選參數(shù)(圖片位置、縮放、url 超鏈接、image_data 圖片字節(jié)流等)。

以插入一張網(wǎng)絡(luò)圖片為例。首先,定義一個(gè)圖片展示可選參數(shù),指定圖片的縮放比、url 超鏈接。

def create_image_options
(x_offset=0, y_offset=0, x_scale=1, y_scale=1, url=None, tip=None, image_data=None,
                         positioning=None):
    """
    插入圖片的參數(shù)配置
    包含:偏移量、縮放比、網(wǎng)絡(luò)圖片鏈接、超鏈接、懸停提示燈
    :param x_offset:
    :param y_offset:
    :param x_scale:
    :param y_scale:
    :param url:
    :param tip:
    :param image_data:
    :param positioning:
    :return:
    """
    image_options = {
        'x_offset': x_offset,
        'y_offset': y_offset,
        'x_scale': x_scale,
        'y_scale': y_scale,
        'url': url,
        'tip': tip,
        'image_data': image_data,
        'positioning': positioning,
    }
    return image_options

image_options = create_image_options
(x_scale=0.5, y_scale=0.5, url='https://www.jianshu.com/u/f3b476549169')

接著,將網(wǎng)絡(luò)圖片轉(zhuǎn)為字節(jié)流:

from io import BytesIO
import ssl

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 insert_network_image(sheet, row_index, column_index, url, filepath, image_options=None):
    """
    插入網(wǎng)絡(luò)圖片
    :param sheet:
    :param row_index:
    :param column_index:
    :param url:
    :param filepath:
    :param image_options:
    :return:
    """
    if row_index < 1 or column_index < 1:
        return "參數(shù)輸入有誤,插入失?。?

    # 獲取圖片字節(jié)流
    image_data = get_image_data_from_network(url)

    if image_options:
        image_options['image_data'] = image_data
    print(image_options)

    sheet.insert_image(row_index - 1, column_index - 1, filepath, image_options)

insert_network_image(self.current_sheet, 1, 1, url, '1.png', image_options4)

使用 set_column() 方法可以設(shè)置列寬,和 openpyxl 類似,有 2 種使用方式,分別是:字符串索引、列索引數(shù)字索引。

def set_column_width(sheet, index_start, index_end, width):
    """
    設(shè)置列寬
    :param sheet:
    :param index_start: 開始位置,從1開始
    :param index_end: 結(jié)束位置
    :param width: 寬度
    :return:
    """
    # 方式二選一
    # self.current_sheet.set_column('A:C', width)

    # 默認(rèn)0代表第一列
    sheet.set_column(index_start - 1, index_end - 1, width)

# 設(shè)置列寬度
# 設(shè)置第1列到第3列的寬度為:100
set_column_width(self.current_sheet, 1, 3, 100)

行高使用 set_row() 方法,傳入行索引和高度即可。

def set_row_height(sheet, row_index, height):
    """
    設(shè)置行高
    :param sheet:
    :param row_index: 行索引,從1開始
    :param height:
    :return:
    """
    sheet.set_row(row_index - 1, height)

# 設(shè)置行高
set_row_height(self.current_sheet, 1, 50)
set_row_height(self.current_sheet, 2, 100)

寫入數(shù)據(jù)完畢之后,將工作簿關(guān)閉,文件會(huì)自動(dòng)保存到本地。

def teardown(self):
    # 寫入文件,并關(guān)閉文件
    self.wb.close()

xlsxwriter 還支持插入圖表,比如:條形圖、柱狀圖、雷達(dá)圖等,受限于篇幅,這部分內(nèi)容就不展開說明了。

其他方式

還有一種比較常見的方式是:xlwings。xlwings 是一款開源免費(fèi)的依賴庫,同時(shí)支持 Excel 文件的讀取、寫入、修改。它功能非常強(qiáng)大,還可以和 Matplotlib、Numpy 和 Pandas 無縫連接,支持讀寫 Numpy、Pandas 數(shù)據(jù)類型;同時(shí),xlwings 可以直接調(diào)用 Excel 文件中 VBA 程序。

需要注意的是,xlwings 依賴于 Microsoft Excel 軟件,所以使用 WPS 的用戶建議直接使用 openpyxl。

另外,還有一個(gè)操作 Excel 比較強(qiáng)大的方式,即:Pywin32。其中,Pywin32 相當(dāng)于調(diào)用 Win 下的系統(tǒng) API 來操作 Excel 文件。

優(yōu)點(diǎn)是:可以處理復(fù)雜圖表的數(shù)據(jù)表;

缺點(diǎn)也非常明顯,包含:速度慢、占用 CPU 高,僅支持 Win 系統(tǒng)。

最后

綜合發(fā)現(xiàn),xlrd/xlwt、openpyxl、xlsxwriter 基本上可以滿足大部分的日常 Excel 文檔操作。


——熱門課程推薦:

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

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

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

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

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

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

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

數(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(), // 加隨機(jī)數(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)的第一個(gè)參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) 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){ //倒計(jì)時(shí)完成 $(".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); }