python读取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表格中的数据   参数: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表格中的数据   参数: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

def main():
   tables = excel_table_byindex()
   for row in tables:
       print row

   tables = excel_table_byname()
   for row in tables:
       print row

if __name__=="__main__":
    main()

我的github地址:http://github.com/biezhi
开源框架Blade:http://github.com/biezhi/blade

目录
相关文章
|
7天前
|
Python
python_读写excel、csv记录
python_读写excel、csv记录
12 0
|
3天前
|
存储 Python Windows
轻松学会openpyxl库,Python处理Excel有如神助
轻松学会openpyxl库,Python处理Excel有如神助
|
3天前
|
NoSQL Python
在Python中,我们可以使用许多库来处理Excel文件
Python处理Excel常用pandas和openpyxl库。pandas的`read_excel`用于读取文件,`to_excel`写入;示例展示了数据框操作。openpyxl则用于处理复杂情况,如多工作表,`load_workbook`加载文件,`iter_rows`读取数据,`Workbook`创建新文件,写入单元格数据后保存。
11 1
|
9天前
|
Python
Python异步编程|PySimpleGUI界面读取PDF转换Excel
Python异步编程|PySimpleGUI界面读取PDF转换Excel
16 1
|
14天前
|
小程序 数据挖掘 iOS开发
Python + Excel 办公自动化 01 —— 硬菜马上就来
Python + Excel 办公自动化 01 —— 硬菜马上就来
21 1
|
14天前
|
存储 Python
终于,手把手教会 HR 实现 Python + Excel 「邮件自动化」发工资条了
终于,手把手教会 HR 实现 Python + Excel 「邮件自动化」发工资条了
22 0
|
14天前
|
数据挖掘 索引 Python
Python 读写 Excel 文件
Python 读写 Excel 文件
12 0
|
20天前
|
Python
Python—提取页面上所有信息输出excel
Python—提取页面上所有信息输出excel
|
20天前
|
开发者 Python
如何让excel 运行python代码
如何让excel 运行python代码
|
1月前
|
Python
【python】提取多个excel的工作簿,生成新的excel
【python】提取多个excel的工作簿,生成新的excel