阿小信大人的头像
Where there is a Python, there is a way. 阿小信大人

Python读写Excel2014-09-02 05:07

http://www.simplistix.co.uk/presentations/python-excel.pdf

http://www.python-excel.org/

############################### write##################################
#-*- coding:utf-8 -*-

import numpy as np
from xlwt import *

book = Workbook()
sheet1 = book.add_sheet('random number')
head = ['normal', 'power', 'gamma', 'SUM']
N = 100
data = np.vstack(
[
    np.random.normal(size=N),
    np.random.power(a=1.0, size=N),
    np.random.gamma(0.9, size=N)
]
)

#创建对齐配置
al = Alignment()
al.horz = Alignment.HORZ_CENTER
al.vert = Alignment.VERT_CENTER

#创建边框配置
borders = Borders()
borders.bottom = Borders.THICK

#创建样式
style = XFStyle()
style.alignment = al
style.borders = borders

#获得第0行
row0 = sheet1.row(0)

#将标题写入第0行,使用所创建的样式
for i, text in enumerate(head):
    row0.write(i, text, style=style)

#写入随机数
for i, line in enumerate(data):
    for j, value in enumerate(line):
        sheet1.write(j+1, i, value)

 #写求和公式,单元格下标从1开始计数
for i in xrange(N):
    sheet1.row(i+1).set_cell_formula(3, Formula("sum(A%s:C%s)"%(i+2, i+2)), calc_flags = 1)

#设置4个列的宽度
for i in xrange(4):
    sheet1.col(i).width = 4000

#设置第0行的高度
sheet1.row(0).height_mismatch = 1
sheet1.row(0).height = 1000
book.save('f:/tmp.xls')



############################### read##################################
>>> from xlrd import open_workbook
>>> book = open_workbook('f:/tmp.xls')
>>> book.nsheets
1
>>> book.sheet_name()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Book' object has no attribute 'sheet_name'
>>> book.sheet_names()
[u'random number']
>>> sheet1 = book.sheets()[0]
>>> sheet1.cell(0,0)
text:u'normal'
>>> sheet1.row(0)
[text:u'normal', text:u'power', text:u'gamma', text:u'SUM']
>>> sheet1.row(1)
[number:-0.48297012653540872, number:0.70425098177925749, number:0.14164759275902736, text......
>>> sheet1.col(1)
[text:u'power', number:0.70425098177925749, number:0.012666695537177697, number:0.04530945......
>>> sheet1.cell(3,1)
number:0.045309456194536191


#####################################################
修改添加数据要用xlutils.copy
>>> from xlrd import *
>>> from xlutils.copy import *
>>> rb = open_workbook('f:/tmp.xls', formatting_info=True)
>>> wb = copy(rb)
>>> ws = wb.get_sheet(0)
>>> ws.write(0, 5, u'去你妈的路口')
>>> wb.save('f:/tmptmp.xls')

获取行数:

>>> sheet1.nrows
36

获取列数:

>>> sheet1.ncols
4

打印全部:

>>> for row in range(mysheet.nrows):
...     for i in mysheet.row(row):
...         print i.value,
...     print
...

若非特别声明,文章均为阿小信的个人笔记,转载请注明出处。文章如有侵权内容,请联系我,我会及时删除。

#Python#  
分享到:
阅读[4011]

你可能也感兴趣的文章推荐

本文最近访客

网友77.*.*.161[捷克]2021-03-06 03:06
网友17.*.*.48[火星]2021-03-06 03:03
网友92.*.*.45[火星]2021-03-06 03:03
网友216.*.*.226[Seattle]2021-03-06 02:46