python 讀寫 excel

介紹

python-excel 是一組用 python 實現的 excel 文件訪問庫, 包括 xlrdxlwtxlutils 三個模塊。 這裏介紹一下它的基本用法,大約須要 15 分鐘閱讀。html

安裝

mac 上的安裝命令python

sudo pip install xlrd
sudo pip install xlwt
sudo pip install xlutils
複製代碼

擴展:其餘的安裝方式參見這裏git

讀文件

讀文件示例代碼以下:github

# -*- coding: utf-8 -*- 

import sys  
reload(sys)  
sys.setdefaultencoding('utf8')  
import xlrd

def read_file(file_path):
	book = xlrd.open_workbook(file_path) #獲得 Excel 文件的 book 對象,實例化對象
	sheet = book.sheet_by_index(0) # 經過 sheet 索引得到 sheet 對象
	ncols = sheet.ncols # 列數
	nrows = sheet.nrows # 行數
	print("row count:{:d}, column count:{:d}".format(nrows, ncols))
	for row in range(nrows):
		print(sheet.row_values(row))

if __name__ == '__main__':
	read_file("test.xls")
複製代碼

固然也能夠逐個 cell 地讀取文件,代碼以下:app

# -*- coding: utf-8 -*- 

from __future__ import print_function
import sys  
reload(sys)  
sys.setdefaultencoding('utf8')  
import xlrd

def read_file(file_path):
	book = xlrd.open_workbook(file_path)
	sheet = book.sheet_by_index(0)
	ncols = sheet.ncols
	nrows = sheet.nrows
	for row in range(nrows):
		for col in range(ncols):
			print(sheet.cell_value(row, col), end='')
			print('\t', end='')
		print("")

if __name__ == '__main__':
	read_file("test.xls")
複製代碼

擴展:xlrd 的 Api 文檔在這裏spa

寫文件

寫文件的示例代碼以下:excel

# -*- coding: utf-8 -*- 
import sys  
reload(sys)  
sys.setdefaultencoding('utf8')  
import xlwt

def get_data():
	data = []
	data.append(["id", "value"])
	for i in range(10):
		col_data = []
		col_data.append(i)
		col_data.append(i * 10)
		data.append(col_data)
	return data

def write_file(file_path, sheet_name, data):
	book = xlwt.Workbook(encoding = 'utf-8')
	sheet = book.add_sheet(sheet_name)
	row = 0
	for row_data in data:
		col = 0
		for cell_data in row_data:
			sheet.write(row, col, cell_data)
			col += 1
		row += 1
	book.save(file_path)

if __name__ == '__main__':
	data = get_data()
	write_file("test.xls", "test sheet", data)
複製代碼

擴展:xlwt 的 Api 文檔在這裏code

過濾文件示例

下面這個過濾文件的示例,是 excel 文件讀寫的綜合應用:orm

# -*- coding: utf-8 -*- 

import sys  
reload(sys)  
sys.setdefaultencoding('utf8')  
import xlrd
import xlwt

# 過濾掉第二列元素等於 keyword 的數據所在行
def filter_file(src_file, src_sheet_name, desc_file, desc_sheet_name, keyword):
	src_book = xlrd.open_workbook(src_file)
	src_sheet = src_book.sheet_by_name(src_sheet_name)

	desc_book = xlwt.Workbook(encoding = 'utf-8')
	desc_sheet = desc_book.add_sheet(desc_sheet_name)

	ncols = src_sheet.ncols
	nrows = src_sheet.nrows
	index = 0
	for row in range(nrows):
		content = src_sheet.cell_value(row, 1)
		if content == keyword:
			continue
		for col in range(ncols):
			desc_sheet.write(index, col, src_sheet.cell_value(row, col))
		index += 1

	desc_book.save(desc_file)	

if __name__ == '__main__':
	filter_file("test.xls", "test sheet", "test_desc.xls", "test sheet", 30)
複製代碼

上述例子中的 test.xls 文件內容爲:htm

id value
0 0
1 10
3 30
2 20
4 40
5 50
6 60
7 70
8 80
9 90

高級用法

xlutils 的使用,留在之後分享。

相關文章
相關標籤/搜索