自動化辦公,用 Python 庫 xlrd 玩轉 Excel

我們日常工作很多時候都會與 Excel 打交道,如果能夠把一些處理 Excel 的重複的機械的步驟變得自動化,那麼我們的工作效率一定可以得到大大提高,今天我們要學習的就是 Python 的 xlrd 庫,以更好的操縱 Excel,首先我們使用 cmd 安裝庫

pip install xlrd

自動化辦公,用 Python 庫 xlrd 玩轉 Excel

我之前就已經裝好了

<section>
<section>
<section>

然後這是我們要使用的 Excel 數據,就是之前爬取天氣那篇文章裡得到的數據

自動化辦公,用 Python 庫 xlrd 玩轉 Excel

weather.xlsx

<section>
<section>
<section>

打開工作簿

xlrd.open_workbook("weather.xlsx")

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

獲取 sheet

這裡一共有四種獲取 sheet 的方法,注意第一種跟後面幾種獲取到的 sheet 的儲存形式是不一樣的

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

操作單元格

注意操作單元格必須是在已經獲取到了 sheet 的情況下對 sheet 中的單元格進行操作,而且不能使用列表形式獲取的 sheet

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

查看某一單元格中數據的數據類型

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

讀取某一單元格中的內容

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

獲取某一單元格的對象

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

操作行

讀取行數,注意這裡的 sheet1 是之前已經獲取到了的表單,不要忘記

sheet1 = wb.sheet_by_name("Sheet1")

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

讀取某一行的單元格長度,注意行數是從 0 開始數

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

讀取某一行的所有單元格的對象,所有對象儲存在列表中

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

讀取某一行的所有單元格的數據類型,結果儲存在一個列表中

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

讀取某一行的所有單元格的數據,結果儲存在一個列表中

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

操作列

讀取表單裡的列數

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

注意這裡並不能像操作行一樣獲取列的單元格個數

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

讀取某一列的所有數據的對象,結果儲存在一個列表中

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

讀取某一列的所有數據的數據類型,結果儲存在一個列表中

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

讀取某一列的所有數據的數據,結果儲存在一個列表中

自動化辦公,用 Python 庫 xlrd 玩轉 Excel
<section>
<section>
<section>

總結

首先,本篇文章的所有數據與代碼已經上傳至 GitHub

網址:https://github.com/WaringHu/toutiao/tree/master/2020.01.07

xlrd 就是用來對 Excel 工作簿進行讀取等最基本功能的庫,從文章中可以清楚,使用 xlrd 讀取數據的基本步驟就是:

  1. 讀取整個 Excel 工作簿
  2. 定位到工作簿中的表單(Sheet)
  3. 再對某一表單的單元格和行列進行操作


分享到:


相關文章: