zoukankan      html  css  js  c++  java
  • python excel读写数据

    python 读取excel内容,包含表格日期处理

    # -*- coding: utf-8 -*-
    import  xlrd
    #读取excel表格
    workbook=xlrd.open_workbook(r'D:demo.xlsx')#打开excel文件
    table = workbook.sheet_by_name('Sheet2')#将文件内容表格化
    rows_num = table.nrows # 获取行
    cols_num = table.ncols # 获取列
    
    res=[]#定义一个数组
    for rows in range(rows_num):
        for cols in range(cols_num):
            cell_value=table.cell(rows,cols).value#获取excel中单元格的内容
            ctype=table.cell(rows,cols).ctype#获取单元格内容的数据类型:ctype:1整型 2浮点型 3日期 4布尔
            if cell_value=='':#判断如果单元格内容为空
                cell_value='--'#设置显示内容为--
                res.append(cell_value)#将内容加入到res数组
            elif ctype ==3:#判断单元格内容为日期类型
                    cell_value=xlrd.xldate_as_datetime(cell_value,0)#将内容转为datetime格式
                    cell_value=cell_value.strftime(("%Y/%m/%d"))#格式转换显示
                    res.append(cell_value)
            elif isinstance(cell_value,unicode):#转码
                    cell_value=cell_value.encode('utf-8')
                    res.append(cell_value)
            elif isinstance(cell_value,float):#转码
                    cell_value = str(cell_value)
                    cell_value = cell_value.decode('utf-8').encode('gb2312')
                    res.append(cell_value)
        res.append('|')
    res = ','.join(res)
    res = res.split('|')
    
    for i in range(len(res)-1):
        print '',i+1,'行数据:',res[i].strip(',')

    读取内容整数变为小数,有2个解决办法:

    1、在excel中数字签名加个英文单引号: '

    2、通过程序代码判断单元格内容的ctype来解决

    if ctype == 2 and cell % 1 == 0.0: # ctype为2且为浮点
    cell = int(cell) # 浮点转成整型
    cell = str(cell) # 转成整型后再转成字符串,如果想要整型就去掉该行

    python写入内容

    # -*- coding: utf-8 -*-
    import xlsxwriter
    import time
    #excel表格写数据
    
    startime=time.time()#获取文件创建时间
    
    workbook=xlsxwriter.Workbook('d:mm.xlsx')#创建一个excel文件
    worksheet=workbook.add_worksheet()#创建一个sheet
    
    title=[u'账号',u'密码']#设置表格title
    worksheet.write_row('A1',title) #将title写入excel
    
    for i in range(1,100):
        num0=bytes(i+1)#因为默认从0开始,所以要加1
        num=bytes(i)
        row='A'+num0#设置行内容
        data=[u'user'+num,num,]#设置列内容
        worksheet.write_row(row,data)#将内容写入单元格
        i+=1#换行
    
    workbook.close()#关闭excel
    
    endtime=time.time()#获取文件关闭时间
    print endtime-startime#计算从创建到写入完成总花费时间
  • 相关阅读:
    关于javascript app框架的几篇文章
    php 开发笔记
    php 图片处理扩展(windows平台)
    [javascript]最短 domready
    javascript小陷阱
    HTML DOM whiteSpace
    40岁后才明白的道理:人一生奋斗余地很有限转载
    [学习笔记]lca倍增
    Django model 字段类型及选项解析转载
    PythonPEP8 风格规范指南
  • 原文地址:https://www.cnblogs.com/yinrw/p/10769791.html
Copyright © 2011-2022 走看看