python excel读写操作单位_python中对Excel进行读写操作
Nullege is a search engine for Python source code
模块安装:分别进入到xlrd和xlwt文件中对setup.py进行安装,安装命令为setup.py install进入python解释器,输入import xlwt,正常无报错即可
下面是一个将Excle文件中的数据读取到普通文本中,和从普通文本写到Excel的一个互换程序:
#encoding:utf8
import xlrd
import xlwt
class openexcel():
#读取Excel表
def rexcel(self,inefile,outfile):
rfile=xlrd.open_workbook(inefile)
#创建索引顺序获得一个工作表
table=rfile.sheet_by_index(0)
nrows=table.nrows
ncols=table.ncols
for i in range(nrows):
print table.row_values(i)
wfile=open(outfile,'w')
for i in range(nrows):
wfile.write(table.cell(i,0).value.encode('utf8')+'\n')
wfile.close()
def wexcel(self,infile,outefile):
rfile=open(infile,'r')
buf=rfile.read().split('\n')
rfile.close()
w=xlwt.Workbook()
sheet=w.add_sheet('sheet1')
for i in range(len(buf)):
print buf[i]
sheet.write(i,0,buf[i].decode('utf8'))
w.save(outefile)
if __name__ == '__main__':
t=openexcel()
t.rexcel('test.xls','jack.txt')
t.wexcel('li1.txt','D:\prada.xls')
test.xls读取到jack.txt中
test.xls:
li1.txt写到d盘prada.xls中
li1.txt:
mx3
1exchange.cc
shenzhen
python
1
2
3
4
5
6
7
8
9
87.05
89.05
――――――――――――――――――――――――
python读写excel的例子
下面是python写excel的例子:
import xlwt
from datetime import datetime
style0 = xlwt.easyxf('font:name 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')
下面的例子读取excel:
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)
print sh.name, sh.nrows, sh.ncols
print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
for rx in range(sh.nrows):
print sh.row(rx)