python 操作 excel

来源:互联网 发布:java heap size 设置 编辑:程序博客网 时间:2024/06/06 12:47

首先,先查看xlrd(对excel文件的read操作)和xlwt(对excel文件的write操作)的版本信息

>>> import xlrd
>>> print xlrd.__VERSION__
0.9.3
>>> import xlwt
>>> print xlwt.__VERSION__
0.7.5
>>> help(xlrd)

PACKAGE CONTENTS
    biffh
    book
    compdoc
    formatting
    formula
    info
    licences
    sheet
    timemachine
    xldate
    xlsx

可以清楚的看到 xlrd是支持 xlsx的读操作。但是xlwt目前不支持对后缀为xlsx的写操作,只支持.xls文件,期待未来调用此模块可以实现哦。

先来介绍下excel文件的读操作


这个是demo.xlsx里面的内容,

vi demo.py



  1 #!/usr/bin/python
  2
  3 # encoding : utf-8
  4
  5 import xlrd
  6
  7 book = xlrd.open_workbook('demo.xlsx')
  8 sheet = book.sheets()[0]
  9 sheet_name = book.sheet_names()[0]
 10 print sheet_name
 11
 12 rows = sheet.nrows
 13 cols = sheet.ncols
 14 print rows, cols
 15
 16 row_value = sheet.row_values(2)
 17 col_value = sheet.col_values(1)
 18 print row_value, col_value
 19
 20 cell = sheet.cell_value(1,1)
 21 tcell = sheet.cell(1,1)
 22 print cell
 23 print tcell

python demo.py

Sheet1
4 2
[u'pear', 1.0] [u'price', 2.0, 1.0, 3.0]
2.0
number:2.0

下面讲一下写excel的操作

vi write_excel.py

  2 #encoding:utf-8
  3
  4 import xlwt
  5 wbk = xlwt.Workbook(encoding='utf-8', style_compression=0)
  6 sheet = wbk.add_sheet('sheet_3', cell_overwrite_ok=True) # cell_overwrite_ok     为true表示可重置单元格内容.
  7
  8 sheet.write(0,0,'Fruit')
  9 sheet.write(0,0,'Flash')
 10 style = xlwt.XFStyle()
 11 font = xlwt.Font()
 12 font.name = 'Times New Roman'
 13 font.bold = True
 14 style.font = font
 15 sheet.write(0,1, 'US TV series', style)
 16 wbk.save('Flash.xls')

python write_excel.py执行后生成Flash.xls的效果图为:


你可以尝试下把 wbk.save('Flash.xls')改为wbk.save('Flash.xlsx')你会发现报错:


写支持xlsx的模块可以自己去搜一下其它模块。

0 0