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')
网友评论