使用Python对Excel进行读写操作
2017-06-05 00:00
585 查看
摘要: 使用Python语言来对Excel进行一些简单的读写操作
在进行编码前,首先要安装xlrd,可以选择到官网 http://pypi.python.org/pypi/xlrd 处下载
读取Excel表格
1.导入xlrd
2.打开excel和获取sheet
3.获取行数或列数
4.获取指定一格的值
写入一个新的Excel表格
1.导入xlwt
2.新建excel和sheet
3.写入
4.保存
对Excel表格进行读写
前面介绍的两个都是单独的读取或写入,如果需要对某excel进行读写,那就要用到xlrd了
1.导入xlrd
2.打开excel和获取sheet
3.进行读写操作
4.保存
例子
以上就是读写的基本操作,如需深入,自行百度谷歌
在进行编码前,首先要安装xlrd,可以选择到官网 http://pypi.python.org/pypi/xlrd 处下载
读取Excel表格
1.导入xlrd
import xlrd
2.打开excel和获取sheet
bk = xlrd.open_workbook('/home/test.xlsx') #通过索引顺序获取 sheet sh = bk.sheets()[0] #通过索引顺序获取 sheet sh = bk.sheet_by_index(0) #通过名称获取sheet sh = bk.sheet_by_name(u'Sheet1')
3.获取行数或列数
#获取行数 nrows = sh.nrows #获取列数 ncols = sh.ncols #获取整行和整列的值(返回数组) sh.row_values(i) sh.col_values(i)
4.获取指定一格的值
#获取第一行第一列的值(即A1) cell_A1 = sh.cell_value(0,0) cell_A1 = sh.cell(0,0).value
写入一个新的Excel表格
1.导入xlwt
import xlwt
2.新建excel和sheet
#新建一个excel文件 file = xlwt.Workbook() #新建一个sheet sh = file.add_sheet('sheet1',cell_overwrite_ok=True)
3.写入
sh.write(0,0,'lalala')
4.保存
file.save(u'file.xls')
对Excel表格进行读写
前面介绍的两个都是单独的读取或写入,如果需要对某excel进行读写,那就要用到xlrd了
1.导入xlrd
import xlrd from xlutils.copy import copy
2.打开excel和获取sheet
rexcel = xlrd.open_workbook("file.xls") # 用wlrd提供的方法读取一个excel文件 sh = rexcel.sheet_by_name("Sheet1")
3.进行读写操作
rows = rexcel.sheets()[0].nrows # 用wlrd提供的方法获得现在已有的行数 excel = copy(rexcel) # 用xlutils提供的copy方法将xlrd的对象转化为xlwt的对象 table = excel.get_sheet(0) # 用xlwt对象的方法获得要操作的sheet value = str(sh.cell_value(0,0)) #用xlrd的方法获取某行某列的值 table.write(0,1,'Yes') #用xlwt的方法来写入
4.保存
#保存为同样的名字,对原excel表格进行覆盖 excel.save('file.xls')
例子
#coding:utf8 import xlrd import MySQLdb import sys reload(sys) sys.setdefaultencoding("utf-8") ''' 将excel中的数据导入到mysql中去 ''' book = xlrd.open_workbook("myexcel.xlsx") sheet = book.sheets()[0] conn=MySQLdb.connect(host=HOST,user=USER,passwd=PASSWD,db=DB,port=PORT,charset="utf8") conn.autocommit(1) cur = conn.cursor() cur.execute("set names utf8") for r in range(1, sheet.nrows): a = sheet.cell(r,0).value b = sheet.cell(r,1).value c = sheet.cell(r,2).value d = sheet.cell(r,3).value sql = "insert into business_area_info (a,b,c,d) value('%s','%s','%s','%s')"%(a,b,c,d) print sql cur.execute(sql)
以上就是读写的基本操作,如需深入,自行百度谷歌
相关文章推荐
- 使用Python对Excel进行读写操作
- [Python笔记] 使用xlrd和xlwt进行简单的excel表格读写操作
- 使用Python对Excel进行读写操作
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd
- 使用python读写操作同一个excel(xlrd,xlwt,xlutils)
- python操作Excel读写(使用xlrd和xlrt)
- python操作Excel读写(使用xlrd和xlrt)
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd/xlwt
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd
- python操作Excel读写--使用xlrd
- java-使用POI对Excel进行读写操作
- python操作Excel读写(使用xlrd和xlrt)