python操作execel主要是读写
读 通过 http://pypi.python.org/pypi/xlrd
写 通过 http://pypi.python.org/pypi/xlwd
下载tar包,解压出来,安装即可,
如果没有权限,将xlrd/xlrd拷贝到当前目录下,也可以使用。
如下是xlrd的使用例子
# -*- coding: utf-8 -*-
import xdrlib ,sys
import xlrd
import sys
def open_excel(file='file.xls'):
try:
handle = xlrd.open_workbook(file)
return handle
except Exception,e:
print str(e)
def parse_table(table):
"""docstring for parse_table"""
print ("table_name %s\t%d\t%d"%(table.name, table.nrows, table.ncols))
#for i in range(table.nrows):
# print table.row_values(i)
#for i in range(table.ncols):
# print table.col_values(i)
for i in range(1, table.nrows):
for j in range(1, table.ncols):
print table.cell(i,j).value
pass
def pass_sheet():
"""docstring for pass_sheet"""
pass if __name__ == '__main__':
handle = open_excel(sys.argv[1])
print handle.sheet_names()
for sheetx in range(handle.nsheets):
table = handle.sheet_by_index(sheetx)
parse_table(table)
如下是xlwd的使用例子
# -*- coding: utf-8 -*-
import xdrlib ,sys
import xlrd
import xlwt
if __name__ == '__main__':
file = sys.argv[1]
#cols
field_name=u'百度 云彩 合理';
handle = xlwt.Workbook() # 注意大写
for i in range(2, len(sys.argv)):
sheet_name= sys.argv[i]
sheet = handle.add_sheet(sheet_name, cell_overwrite_ok=True) #新建表格,True表示对同一个单元操作不报错
fd = open(sys.argv[i], "r")
fields = field_name.split() # title名
for j in range(len(fields)):
sheet.write(0, j, fields[j])
colum = 1;
for line in fd.readlines():
fields = line.split()
for j in range(len(fields)):
sheet.write(colum, j, fields[j]) # 写值
colum = colum + 1
fd.close()
handle.save(file) #保存