<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          最全總結(jié) | 聊聊 Python 辦公自動化之 Excel(下)

          共 9173字,需瀏覽 19分鐘

           ·

          2021-08-24 14:45

          聊聊 Python 數(shù)據(jù)處理全家桶(Memca 篇)
          ????關(guān)注后回復(fù) “進群” ,拉你進程序員交流群????

          作者丨星安果

          來源丨AirPython

          1. 前言

          前面談到 Python 處理 Excel 文件最常見的兩種方式,即:xlrd/xlwt、openpyxl

          其中,

          xlrd/xlwt 這一組合,xlrd 可以負責(zé)讀取數(shù)據(jù),而 xlwt 則負責(zé)寫入數(shù)據(jù),缺點是不支持 xlsx

          openpyxl 同時支持對 Excel 文檔的讀取、寫入操作,缺點是不支持 xls

          本篇文章將繼續(xù)聊聊 Python 操作 Excel 文檔的其他幾種方式

          2. xlsxwriter

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

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

          首先安裝 xlsxwriter 的依賴包

          # 安裝依賴包
          pip3 install xlsxwriter

          xlsxwriter 提供了 Workbook(filename) 方法,用于創(chuàng)建一個工作簿對象

          使用工作簿對象的 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

          接著,就可以往某個 Sheet 單元格中寫入數(shù)據(jù)了

          如果需要定制單元格的樣式,比如:字體大小、字體、顏色、背景、是否加粗等,可以使用工作簿對象的 add_format() 方法創(chuàng)建一個樣式

          def create_format_styles(wb, format_stuyles):
              """
              創(chuàng)建一個樣式,包含:字體大小、字體、顏色、背景、是否加粗等
              :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)建標題字體樣式
          title_font_style = create_format_styles(self.wb, self.title_style)

          Sheet 對象的 write(...) 函數(shù)用于向單元格中寫入數(shù)據(jù),參數(shù)包含:行索引、列索引、值、字體樣式等

          需要注意的是,默認 xlsxwriter 的行索引、列索引都是從 0 開始,即:0 代表第一行

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

          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:
                  # 注意:默認xlsxwriter的行索引、列索引從0開始
                  sheet.write(row_index - 1, column_index - 1, value, format_styles)

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

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

          使用的方法是:insert_image()

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

          以插入一張網(wǎng)絡(luò)圖片為例

          首先,定義一個圖片展示可選參數(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, 11, 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)

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

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

          行高使用 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, 150)
          set_row_height(self.current_sheet, 2100)

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

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

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

          3. 其他方式

          還有一種比較常見的方式是xlwings

          xlwings 是一款開源免費的依賴庫,同時支持 Excel 文件的讀取、寫入、修改

          它功能非常強大,還可以和 Matplotlib、Numpy 和 Pandas 無縫連接,支持讀寫 Numpy、Pandas 數(shù)據(jù)類型;同時,xlwings 可以直接調(diào)用 Excel 文件中 VBA 程序

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

          官方文檔:

          https://docs.xlwings.org/zh_CN/latest/quickstart.html

          另外,還有一個操作 Excel 比較強大的方式,即:Pywin32

          其中,

          Pywin32 相當于調(diào)用 Win 下的系統(tǒng) API 來操作 Excel 文件

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

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

          4. 最后

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

          -End-

          最近有一些小伙伴,讓我?guī)兔φ乙恍?nbsp;面試題 資料,于是我翻遍了收藏的 5T 資料后,匯總整理出來,可以說是程序員面試必備!所有資料都整理到網(wǎng)盤了,歡迎下載!

          點擊??卡片,關(guān)注后回復(fù)【面試題】即可獲取

          在看點這里好文分享給更多人↓↓

          瀏覽 26
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  www.豆花豆花视频网站 | 欧美特级黄片在线播放 | 水多多成人 | 香蕉社区在线观看 | 亚洲熟女www一区二区三区 |