python 操作 excel

python操作execel主要是读写

读 通过 http://pypi.python.org/pypi/xlrd

写 通过 http://pypi.python.org/pypi/xlwd

下载tar包,解压出来,安装即可,

如果没有权限,将xlrd/xlrd拷贝到当前目录下,也可以使用。

如下是xlrd的使用例子

 1 # -*- coding: utf-8 -*-
 2 import xdrlib ,sys
 3 import xlrd
 4 import sys
 5 def open_excel(file=file.xls):
 6     try:
 7         handle = xlrd.open_workbook(file)
 8         return handle
 9     except Exception,e:
10         print str(e)
11 def parse_table(table):
12   """docstring for parse_table"""
13   print ("table_name %s\t%d\t%d"%(table.name, table.nrows, table.ncols))
14   #for i in range(table.nrows):
15   #  print table.row_values(i)
16   #for i in range(table.ncols):
17   #  print table.col_values(i)
18   for i in range(1, table.nrows):
19     for j in range(1, table.ncols):
20       print table.cell(i,j).value
21   pass
22 def pass_sheet():
23   """docstring for pass_sheet"""
24   pass
25 
26 if __name__ == __main__:
27   handle = open_excel(sys.argv[1])
28   print handle.sheet_names()
29   for sheetx in range(handle.nsheets):
30     table = handle.sheet_by_index(sheetx)
31     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) #保存

 

 

python 操作 excel,布布扣,bubuko.com

python 操作 excel

上一篇:Java-- 匿名类


下一篇:黑马程序员_JAVA UDP网络编程学习笔记