1. 程式人生 > 實用技巧 >使用Python對Excel進行讀寫操作

使用Python對Excel進行讀寫操作

學習Python的過程中,我們會遇到Excel的讀寫問題。這時,我們可以使用xlwt模組將資料寫入Excel表格中,使用xlrd模組從Excel中讀取資料。下面我們介紹如何實現使用Python對Excel進行讀寫操作。

Python版:3.5.2

通過pip安裝xlwt,xlrd這兩個模組,如果沒有安裝的話:

pip install xlwt

pip install xlrd

一、對Excel檔案進行寫入操作:


# -*- conding:utf-8 -*-
#How to write to an Excel using xlwt module
import xlwt
#建立一個Wordbook物件,相當於建立了一個Excel檔案
book = xlwt.Workbook(encoding = "utf-8", style_compression = 0)
#建立一個sheet物件,一個sheet物件對應Excel檔案中的一張表格
sheet = book.add_sheet("sheet1", cell_overwrite_ok = True)
#向表sheet1中新增資料
sheet.write(0, 0, "EnglishName") #其中,"0, 0"指定表中的單元格,"EnglishName"是向該單元格中寫入的內容
sheet.write(1, 0, "MaYi")
sheet.write(0, 1, "中文名字")
sheet.write(1, 1, "螞蟻")
#最後,將以上操作儲存到指定的Excel檔案中
book.save("name.xls")

二、對Excel檔案進行讀取操作:

import xlrd
# 開啟指定路徑中的xls檔案,得到book物件
xls_file = "name.xls"
#開啟指定檔案
book = xlrd.open_workbook(xls_file)
# 通過sheet索引獲得sheet物件
sheet1 = book.sheet_by_index(0)
# # 獲得指定索引的sheet名
# sheet1_name = book.sheet_names()[0]
# print(sheet1_name)
# # 通過sheet名字獲得sheet物件
# sheet1 = book.sheet_by_name(sheet1_name)
# 獲得行數和列數
# 總行數
nrows = sheet1.nrows
#總列數
ncols = sheet1.ncols
# 遍歷打印表中的內容
for i in range(nrows):
  for j in range(ncols):
    cell_value = sheet1.cell_value(i, j)
    print(cell_value, end = "\t")
  print("")