Python讀寫操作Excel文檔(xlrd/xlwt)

Python可以通過兩個第三方包來操作Excel文檔:

xlrd:https://pypi.python.org/pypi/xlrd
xlwt:https://pypi.python.org/pypi/xlwt

兩個包都可以通過pip安裝:

pip install xlrd
pip install xlwt

xlrd包可以支持xlsx格式的文檔,而xlwt只能支持2003之前的版本。

xlrd Quick Start

import xlrd
# 打開文檔
book = xlrd.open_workbook("myfile.xls")

print "The number of worksheets is", book.nsheets
print "Worksheet name(s):", book.sheet_names()

# 打開工作表(三種方法)
sh = book.sheet_by_index(0)
sh = book.sheets()[0]
sh = book.sheet_by_name('sheet1')

# 操作行列和單元格
print sh.name, sh.nrows, sh.ncols
print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
print "Cell D30 is", sh.cell(29,3).value

# 循環
for rx in range(sh.nrows):
    print sh.row(rx)
# Refer to docs for more details.
# Feedback on API is welcomed.

xlwt Quick Start

import xlwt
from datetime import datetime

style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on',
    num_format_str='#,##0.00')
style1 = xlwt.easyxf(num_format_str='D-MMM-YY')

wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')

ws.write(0, 0, 1234.56, style0)
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 0, 1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))

wb.save('example.xls')
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容