python 获取excel表内容 生成php数组

需求:

生成:同时处理数字类型,比如3 不能显示为3.0

[

  ['type'=>3,'da_name'=>福建省平潭拓至美装饰工程有限公司,'da_aka'=>福建省平潭拓至美装饰工程有限公司,'da_alias'=>无],
  ['type'=>3,'da_name'=>福州慕水卫装饰工程有限公司,'da_aka'=>福州慕水卫装饰工程有限公司,'da_alias'=>无].

]

 

# -*- coding: utf-8 -*-
import xlrd
from datetime import date, datetime


def read_excel():
    #获取文件
    ExcelFile = xlrd.open_workbook(r'C:\Users\kevin\Desktop\火理财机构信息.xlsx')

    # 获取目标EXCEL文件sheet名
    # print(ExcelFile.sheet_names())

    # 若有多个sheet,则需要指定读取目标sheet例如读取sheet2

    # sheet2_name=ExcelFile.sheet_names()[1]
    # print(sheet2_name);

    # 获取sheet内容【1.根据sheet索引2.根据sheet名称】

    sheet=ExcelFile.sheet_by_index(0)
    # sheet = ExcelFile.sheet_by_name('TestCase002')

    # 打印sheet的名称,行数,列数
    # print(sheet.name, sheet.nrows, sheet.ncols)

    finalDict = "["
    firstRow = sheet.row_values(1)
    for row in range(2,sheet.nrows):
        eachrow = '['
        for point in range(0,len(sheet.row_values(row))):
            eachcell = sheet.row_values(row)[point]
            if isinstance(eachcell,str):#如果是字符串
                eachcell = eachcell.strip('\n')
                eachrow += "'"+firstRow[point]+"'" + "=>" + eachcell + ','
            else:#数字或者浮点
                if int(eachcell) == float(eachcell):
                    eachcell = int(eachcell)
                eachrow += "'" + firstRow[point] + "'" + "=>" + str(eachcell) + ','



        eachrow+='],'+'\n'
        finalDict+=eachrow
    finalDict += '];'
    print(finalDict)
    # # 获取整行或者整列的值 .
    #
    # rows = sheet.row_values(2)  # 第三行内容
    #
    # cols = sheet.col_values(1)  # 第二列内容
    #
    # print
    # cols, rows
    #
    # # 获取单元格内容
    #
    # print
    # sheet.cell(1, 0).value.encode('utf-8')
    #
    # print
    # sheet.cell_value(1, 0).encode('utf-8')
    #
    # print
    # sheet.row(1)[0].value.encode('utf-8')
    #
    # # 打印单元格内容格式
    #
    # print
    # sheet.cell(1, 0).ctype
    #
    # if__name__ == '__main__':
    #

read_excel()

 

posted on 2018-03-24 11:58  一只猪儿虫  阅读(561)  评论(0编辑  收藏  举报