yunshichen

我相信人生是值得活的,尽管人在一生中必须遭受痛苦,卑劣,残酷,不幸和死亡的折磨,我依然深信如此.但我认为人生不一定要有意义,只是对一些人而言,他们可以使人生有意义. ---J 赫胥黎

Python 读写 Excel


基本上, 这个网页已经说明一切了: http://pypi.python.org/pypi/xlrd

等有时间再把这个页面写漂亮,现在先记一些代码.

读Excel

先建个simple.xls

from xlrd import open_workbook

wb 
= open_workbook('simple.xls','rb')
for s in wb.sheets():
    
print 'Sheet:',s.name
    
for row in range(s.nrows):
        values
=[]
        
for col in range(s.ncols):
            values.append(s.cell(row,col).value)
        
print ",".join(values)
    
print

        


写Excel

from tempfile import TemporaryFile
from xlwt import Workbook

book 
= Workbook()
sheet1 
= book.add_sheet('Sheet 1')
book.add_sheet(
'Sheet 2')
sheet1.write(0,0,
'A1')
sheet1.write(0,
1,'B1')

row1 
= sheet1.row(1)
row1.write(0,
'A2')
row1.write(
1,'B2')

sheet1.col(0).width 
= 10000

sheet2 
= book.get_sheet(1)
sheet2.row(0).write(0,
'Sheet 2 A1')
sheet2.row(0).write(
1,'Sheet 2 B1')
sheet2.flush_row_data()

sheet2.write(
1,0,'Sheet 2 A3')
sheet2.col(0).width 
= 5000
sheet2.col(0).hidden 
= True

book.save(
'simple2.xls')
book.save(TemporaryFile())



posted on 2010-03-16 01:20 Chenyunshi 阅读(8317) 评论(2)  编辑 收藏 引用 所属分类: Python2.5/2.6

评论

# re: Python 读写 Excel[未登录] 2013-12-14 18:44 xj

Traceback (most recent call last):
File "readExcel.py", line 10, in <module>
print ','.join(values)
TypeError: sequence item 0: expected string, float found
  回复  更多评论   

# re: Python 读写 Excel[未登录] 2013-12-14 18:45 xj


楼主,按照你的那个代码貌似会报错:
python报错:
python readExcel.py
Sheet: 工作表1
c1,c2
Traceback (most recent call last):
File "readExcel.py", line 10, in <module>
print ','.join(values)
TypeError: sequence item 0: expected string, float found

代码:
from xlrd import open_workbook

wb = open_workbook('testc12.xls','rb')
for s in wb.sheets():
print 'Sheet:',s.name
for row in range(s.nrows):
values=[]
for col in range(s.ncols):
values.append(s.cell(row,col).value)
print ','.join(values)
print
  回复  更多评论   

只有注册用户登录后才能发表评论。
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿(7)

随笔分类

随笔档案

文章分类

相册

搜索

最新评论

阅读排行榜

评论排行榜