首页 > 代码库 > Pyhon 读写excel简单示例

Pyhon 读写excel简单示例

一、前提准备
1 安装pip: sudo apt-get install python-pip
2 安装python的xlrd模块: sudo pip install xlrd
3 安装python的pyExcelerator模块: sudo pip install pyExcelerator
二、目录结构
1 static目录
3 readExcel.py
4 writeExcel.py

三、readExcel.py内容

#!usr/bin/python
<!-- lang: python -->
#-*- coding:utf-8 -*-
<!-- lang: python -->
__author__ = ‘suiyc‘
<!-- lang: python -->

<!-- lang: python -->
import os
<!-- lang: python -->
import xlrd
<!-- lang: python -->

<!-- lang: python -->
static_path=os.path.join(os.path.dirname(__file__), "static") #设置静态路径
<!-- lang: python -->
file_name = "%s/sida.xls" %  static_path
<!-- lang: python -->

<!-- lang: python -->
bk = xlrd.open_workbook(file_name)
<!-- lang: python -->
shxrange = range(bk.nsheets)
<!-- lang: python -->

<!-- lang: python -->
try:
<!-- lang: python -->
    sh = bk.sheet_by_name(‘Sheet1‘)
<!-- lang: python -->
except:
<!-- lang: python -->
    print ‘no sheet in %s named Sheet1‘ % file_name
<!-- lang: python -->

<!-- lang: python -->
#get rows num
<!-- lang: python -->
nrows = sh.nrows
<!-- lang: python -->
#get colum num
<!-- lang: python -->
ncols = sh.ncols
<!-- lang: python -->

<!-- lang: python -->
print "nrows: %d, ncols: %d" %(nrows, ncols)
<!-- lang: python -->

<!-- lang: python -->
# read the first row and the first colum data
<!-- lang: python -->
cell_value = http://www.mamicode.com/sh.cell_value(0,0)> 

四、writeExcel.py内容展示

#!usr/bin/python
<!-- lang: python -->
#-*- coding:utf-8 -*-
<!-- lang: python -->
__author__ = ‘suiyc‘
<!-- lang: python -->

<!-- lang: python -->
import os
<!-- lang: python -->
from pyExcelerator import *
<!-- lang: python -->

<!-- lang: python -->
static_path=os.path.join(os.path.dirname(__file__), "static") #设置静态路径
<!-- lang: python -->
file_name = "%s/test.xls" %  static_path
<!-- lang: python -->

<!-- lang: python -->
w = Workbook() #创建一个工作薄
<!-- lang: python -->
ws = w.add_sheet(‘Hey, Haders‘)#创建一个工作表
<!-- lang: python -->
ws.write(0,0,‘name‘) #在第1行第1列写入name
<!-- lang: python -->
ws.write(0,1,‘age‘)#在第1行第2列写入age
<!-- lang: python -->
ws.write(0,1,‘gender‘)#在第1行第2列写入gender
<!-- lang: python -->
ws.write(1,0,‘Kimi‘) #在第2行第1列写入Kimi
<!-- lang: python -->
ws.write(1,1,‘20‘)#在第2行第2列写入20
<!-- lang: python -->
ws.write(1,1,‘male‘)#在第2行第2列写入male
<!-- lang: python -->
w.save(file_name)

Pyhon 读写excel简单示例