天天看點

python讀寫excel檔案

一、概述

Python操作excel的三個工具包如下,注意,隻能操作.xls,不能操作.xlsx。

xlrd: 對excel進行讀相關操作

xlwt: 對excel進行寫相關操作

xlutils: 對excel讀寫操作的整合

這三個工具包都可以直接使用pip進行下載下傳:

sudo pip install xlrdsudo 

pip install xlwtsudo 

pip install xlutils

二、使用xlrd子產品讀取已有的excel檔案内容

    xlrd是用來從一個excel檔案中讀取内容的子產品

代碼如下:

導入

import xlrd

打開excel

data = xlrd.open_workbook('demo.xls') #注意這裡的workbook首字母是小寫

檢視檔案中包含sheet的名稱

data.sheet_names()

得到第一個工作表,或者通過索引順序 或 工作表名稱

table = data.sheets()[0]

table = data.sheet_by_index(0)

table = data.sheet_by_name(u'Sheet1')

擷取行數和列數

nrows = table.nrows

ncols = table.ncols

擷取整行和整列的值(數組)

table.row_values(i)

table.col_values(i)

循環行,得到索引的清單

for rownum in range(table.nrows):

print table.row_values(rownum)

單元格

cell_A1 = table.cell(0,0).value

cell_C4 = table.cell(2,3).value

分别使用行列索引

cell_A1 = table.row(0)[0].value

cell_A2 = table.col(1)[0].value

簡單的寫入

row = 0

col = 0

ctype = 1 # 類型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

value = 'lixiaoluo'

xf = 0 # 擴充的格式化 (預設是0)

table.put_cell(row, col, ctype, value, xf)

table.cell(0,0) # 文本:u'xxxx'

table.cell(0,0).value # 'yyyy'

三、使用xlwd子產品寫内容儲存到新的excel檔案中

    xlwt隻能建立一個全新的excel檔案,然後對這個檔案進行寫入内容以及儲存。但是大多數情況下我們希望的是讀入一個excel檔案,然後進行修改或追加,這個時候就需要xlutils了。

導入xlwt

import xlwt

建立一個excel檔案

file = xlwt.Workbook() #注意這裡的Workbook首字母是大寫,無語吧

建立一個sheet

table = file.add_sheet('sheet name')

寫入資料table.write(行,列,value)

table.write(0,0,'test')

如果對一個單元格重複操作,會引發

returns error:# Exception: Attempt to overwrite cell:# sheetname=u'sheet 1' rowx=0 colx=0

是以在打開時加cell_overwrite_ok=True解決

table = file.add_sheet('sheet name',cell_overwrite_ok=True)

儲存檔案

file.save('demo.xls')

另外,使用style

style = xlwt.XFStyle() #初始化樣式

font = xlwt.Font() #為樣式建立字型

font.name = 'Times New Roman'

font.bold = True

style.font = font #為樣式設定字型

table.write(0, 0, 'some bold Times text', style) # 使用樣式

四、使用xlutils子產品追加寫入内容到已有的excel檔案中(新内容追加到已有内容裡面)

# -*- coding: cp936 -*-

import xlwt;

import xlrd;

#import xlutils;

from xlutils.copy import copy;

#用xlrd提供的方法讀取一個已經存在的excel檔案,使用"formatting_info=True"保持源檔案格式不變

rexcel = xlrd.open_workbook("file.xls",formatting_info=True)

#用wlrd提供的方法獲得現在已有的行數

rows = rexcel.sheets()[0].nrows

#cols = rexcel.sheets()[0].ncols

#用xlutils提供的copy方法将xlrd的對象轉化為xlwt的對象

excel = copy(rexcel)

#用xlwt對象的方法獲得要操作的excel中的表名(sheet),0表示第一張表,1表示第二張表。

table = excel.get_sheet(0)

values = ['1','2','3']

row = rows

print row

for value in values:

# xlwt對象的寫方法,參數分别是行、列、值

    table.write(row,0,value)

    table.write(row,1,"haha")

    table.write(row,2,"lala")

    row+=1

# xlwt對象的儲存方法,這時便覆寫掉了原來的excel  

excel.save("file.xls")

本文轉自 老鷹a  51CTO部落格,原文連結:http://blog.51cto.com/laoyinga/1947978