Python读写操作Excel文档(xlrd/xlwt)

作者: 科斯莫耗子 | 来源:发表于2016-07-21 20:20 被阅读747次

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')

相关文章

网友评论

  • Mo丶染洛凉:为什么下面不注释呢,完全和官方一样示例呀
  • 掂吾掂:其实我想说...如果是直接copy官网上面的demo...在某些代码面前加一些个人见解也好...如果就这样直接贴上去...其实对于一个看不懂的人来说...其实意义不大...
    科斯莫耗子:@掂吾掂 一开始是记录给自己看的,有时间补案例吧
  • 舞月光:很好
    科斯莫耗子:@舞月光 谢谢

本文标题:Python读写操作Excel文档(xlrd/xlwt)

本文链接:https://www.haomeiwen.com/subject/bxnbjttx.html