python處理Excel

pythontab發表於2014-12-15

Python中一般使用xlrd庫來讀取Excel檔案,使用xlwt庫來生成Excel檔案,使用xlutils庫複製和修改Excel檔案。這三個庫只支援到Excel2003。

python-excel主頁地址:http://www.python-excel.org/

xlrd

地址:https://pypi.python.org/pypi/xlrd

github地址:https://github.com/python-excel/xlrd

開啟excel檔案,獲取一個Book()物件:

import xlrd
book = xlrd.open_workbook("myfile.xls")

獲取sheets數目:

>>> book.nsheets
3

獲取sheets列表:

>>> book.sheets()
[<xlrd.sheet.Sheet object at 0x01A93970>, <xlrd.sheet.Sheet object at 0x01A93950>, <xlrd.sheet.Sheet object at 0x01A93E70>]

獲取sheets name列表:

>>> book.sheet_names()
[u'Sheet1', u'Sheet2', u'Sheet3']

獲取Book()中的Sheet:

sheet = book.sheets()[0]          #sheets返回一個sheet列表
sheet = book.sheet_by_index(0)    #透過索引順序獲取
sheet = book.sheet_by_name(u'Sheet1')#透過名稱獲取

獲取行數,列數,名字:

>>> sheet.nrows
1002
>>> sheet.ncols
11
>>> sheet.name
u'Sheet1'

獲取某行,某行值列表,某列,某列值列表:

sheet.row(i)
sheet.row_values(i)
sheet.col(i)
sheet.col_values(i)

獲取單元格的值:

cell = sheet.cell(i,j)
cell_value = sheet.cell_value(i,j)
cell_value = sheet.cell(i,j).value

需要注意的是,用xlrd讀取excel是不能對其進行操作的:xlrd.open_workbook()方法返回xlrd.Book型別,是隻讀的,不能對其進行操作。

xlwt

地址:http://pypi.python.org/pypi/xlwt,適用於python2.3-2.7

xlwt-future:https://pypi.python.org/pypi/xlwt-future/0.8.0,適用於Python 2.6-3.3

github地址:https://github.com/python-excel/xlwt

建立一個Excel檔案並建立一個Sheet:

from xlwt import *
book = Workbook()
sheet = book.add_sheet('Sheet1')
book.save('myExcel.xls')

Workbook類可以有encoding和style_compression引數。

encoding,設定字元編碼,style_compression,表示是否壓縮。這樣設定:w = Workbook(encoding='utf-8'),就可以在excel中輸出中文了。預設是ascii。

向sheet寫入內容:

sheet.write(r, c, label="", style=Style.default_style)

簡單寫入:

sheet.write(0, 0, label = 'Row 0, Column 0 Value')

設定格式寫入:

font = xlwt.Font() # 字型
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
style = xlwt.XFStyle() # 建立一個格式
style.font = font # 設定格式字型
sheet.write(1, 0, label = 'Formatted value', style) # Apply the Style to the Cell
book.save('myExcel.xls')

寫入日期:

style = xlwt.XFStyle()
style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
sheet.write(0, 0, datetime.datetime.now(), style)

寫入公式:

sheet.write(0, 0, 5) # Outputs 5
sheet.write(0, 1, 2) # Outputs 2
sheet.write(1, 0, xlwt.Formula('A1*B1')) # 輸出 "10" (A1[5] * A2[2])
sheet.write(1, 1, xlwt.Formula('SUM(A1,B1)')) # 輸出 "7" (A1[5] + A2[2])

寫入連結:

sheet.write(0, 0, xlwt.Formula('HYPERLINK("http://www.google.com";"Google")')) #輸出 "Google"連結到http://www.google.com

xlutils

地址:http://pythonhosted.org/xlutils/

github地址:https://github.com/python-excel/xlutils

xlutils.copy.copy(wb)

複製一個xlrd.Book物件,生成一個xlwt.Workbook物件,可以對xlwt.Workbook進行修改。

from xlrd import open_workbook
from xlutils.copy import copy
book = open_workbook('myExcel.xls')
wbook = copy(book)  #wbook即為xlwt.WorkBook物件
wsheet = wbook.get_sheet(0)  #透過get_sheet()獲取的sheet有write()方法
wsheet.write(0, 0, 'value')
wb.save('myExcel.xls')


相關文章