要通过Python实现Excel文件的读写,首先需要安装xlrd库,该库支持读取Excel文件,而xlwt和openpyxl库则支持写入。安装方法如下:
pip install xlrd
读取Excel文件时,可以使用open_excel函数。该函数接收Excel文件路径作为参数,返回一个包含工作簿数据的对象。
参考代码如下:
# -*- coding: utf-8 -*-
import xdrlib ,sys
import xlrd
def open_excel(file= 'file.xls'): try:
data = xlrd.open_workbook(file)
return data
except Exception,e: print str(e)
根据索引获取Excel表格中的数据,可以使用excel_table_byindex函数。该函数接收Excel文件路径、表头列名所在行索引以及表的索引作为参数。
参考代码如下:
#根据索引获取Excel表格中的数据 参数:file:Excel文件路径 colnameindex:表头列名所在行的所以 ,by_index:表的索引
def excel_table_byindex(file= 'file.xls',colnameindex=0,by_index=0):
data = open_excel(file)
table = data.sheets()[by_index]
nrows = table.nrows #行数
ncols = table.ncols #列数
colnames = table.row_values(colnameindex) #某一行数据
list =[]
for rownum in range(1,nrows):
row = table.row_values(rownum)
if row:
app = {}
for i in range(len(colnames)):
app[colnames[i]] = row[i]
list.append(app)
return list
根据名称获取Excel表格中的数据,可以使用excel_table_byname函数。该函数接收Excel文件路径、表头列名所在行索引以及Sheet1名称作为参数。
参考代码如下:
#根据名称获取Excel表格中的数据 参数:file:Excel文件路径 colnameindex:表头列名所在行的所以 ,by_name:Sheet1名称
def excel_table_byname(file= 'file.xls',colnameindex=0,by_name=u'Sheet1'):
data = open_excel(file)
table = data.sheet_by_name(by_name)
nrows = table.nrows #行数
colnames = table.row_values(colnameindex) #某一行数据
list =[]
for rownum in range(1,nrows):
row = table.row_values(rownum)
if row:
app = {}
for i in range(len(colnames)):
app[colnames[i]] = row[i]
list.append(app)
return list
通过上述函数,可以方便地读取Excel文件中的数据。在实际应用中,可以根据需求进行相应的扩展和修改。
温馨提示:答案为网友推荐,仅供参考