美文网首页
2019-03-29

2019-03-29

作者: Snowdrop_99 | 来源:发表于2019-03-29 17:24 被阅读0次

    近期在做一些使用对excel表格提取的工作,在进行大批量的excel数据提取时,python的速度真是远超matlab。

    在使用python处理excel文件时,需要用到xlrd模块对文件进行读取之类的操作,xlwt模块进行写入的操作,具体代码如下:

    import xlrd

    import xlwt

    def open_excel(file):

    try:

    data=xlrd.open_workbook(file)

    return data

    except Exception as e:

    print (str(e))

    #写入新的excel表

    def write_excel(file='baro2.xls',list=[]):

    book=xlwt.Workbook()#创建一个工作工作簿

    sheet1=book.add_sheet('sheet1')#在上面建立sheet1

    #从第0行开始将list中的row写入新的sheet中

    i=0

    #list中的每一行

    for app in list:

    j=0

    for x in app:        #每一行中的每一列中的元素x

    sheet1.write(i,j,x)

    j=j+1#列数递增

    i=i+1#行数递增

    book.save(file)#保存文件

    def excel_table_byindex(file,colnameindex=0,by_index=0):

    data=open_excel(file)#打开文件

    table=data.sheets()[0]#取工作簿上的第一个sheet

    nrows=table.nrows#行数和列数

    ncols=table.ncols

    colnames=table.row_values(colnameindex) #默认第0行的值

    list=[]#创建list来存每一行的值

    list.append(table.row_values(0))#将第一个标题栏加入到list中

    #将满足条件的行加入到list中

    for rownum in range(1,nrows):#从标题栏的下一行开始遍历每一个行

    row=table.row_values(rownum)#某一行的数据

    if row:                #如果这一行存在的话

    if float(table.cell(rownum,1).value)>0.0:

    list.append(row)

    write_excel('baro2.xls',list)#写入新的excel表

    return list

    def main():

    tables=excel_table_byindex('baro.xls')

    #打印每一行

    for row in tables:

    print(row)

    if __name__ =='__main__':

    main()

    相关文章

      网友评论

          本文标题:2019-03-29

          本文链接:https://www.haomeiwen.com/subject/ihtrbqtx.html