python解析excel

import xlrd, base64
excel_obj = xlrd.open_workbook(file_contents=base64.decodestring(filename))。#打开要解析的excel
sheets = excel_obj.sheets() #读取sheet表内容
for sh in sheets:
for row in range(1, sh.nrows):
row_n = row + 1
name = sh.cell(row, 0).value #第一列的数据
size = sh.cell(row, 1).value #第二列的数据
material = sh.cell(row, 2).value #第三列的数据
           #python读取excel中单元格的内容返回的有5种类型,即上面例子中的ctype:
# ctype: 0: empty, 1:string, 2:number, 3:date, 4:boolean, 5 :error
            ctype = sheet.cell(i, j).ctype  # 表格的数据类型
            cell = sheet.cell_value(i, j)
            if ctype == 2 and cell % 1 == 0:  # 如果是整形
               cell = int(cell)
            elif ctype == 3:
               # 转成datetime对象
               date = datetime(*xldate_as_tuple(cell, 0))
               cell = date.strftime('%Y/%d/%m %H:%M:%S')
            elif ctype == 4:
               cell = True if cell == 1 else False




# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import UserError
from odoo.tools.translate import _
import xlrd, base64, datetime



class ImportWizard(models.TransientModel):
    _name = 'base.import.line.wizard'
    _description = u'导入数据模板'

    data = fields.Binary(u'导入Excel文件')

    @api.multi
    def btm_confirm(self):
        import_model=self.env['lot.element.composition']
        product_obj=self.env['product.product']
        excel_obj=xlrd.open_workbook(file_contents=base64.decodestring(self.data))
        # sheets=excel_obj.sheets()  读取所有sheet表
        sh=excel_obj.sheets()[0]   #读取第一个sheet表
        for row in range(1,sh.nrows): #循环所有行,从第二行读起
            # sh.cell(row, 0).ctype #读取该单元格数据类型
            product_name=sh.cell(row,0).value  #取第一列数据
            lot_name = sh.cell(row,1).value
            qty = sh.cell(row,2).value
            record={
                'product':1,  #todo
                'lot':lot_name,
                'qty':qty
            }
            import_model.sudo().create(record)
        # 导入数据后,刷新当前页面
        return { 'type': 'ir.actions.client', 'tag': 'reload', }

 

 
 


更对内容参考:https://www.cnblogs.com/xxiong1031/p/7069006.html
posted @ 2020-03-28 20:23  何双新  阅读(1131)  评论(0编辑  收藏  举报