Odoo中文网|Odoo实施培训

 找回密码
 立即注册
搜索
热搜: Odoo OpenERP 实施
查看: 7525|回复: 0
打印 上一主题 下一主题

odoo读写excel

[复制链接]

17

主题

19

帖子

75

积分

注册会员

Rank: 2

积分
75
跳转到指定楼层
楼主
发表于 2015-12-26 10:45:14 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
odoo经常要导入和导出数据,excel是比较常见的文档,读写excel,上代码:
  1. # -*- coding: utf-8 -*-
  2. # author:ghoti
  3. import xlrd
  4. import xlwt
  5. import base64
  6. import cStringIO
  7. class Read_Excel:
  8.     '''
  9.                 根据索引获取Excel表格中的数据   参数:file_name:Excel文件路径;file_contents:二进制文件/字符串
  10.        col_n:表头列名所在行数 ;del_n:表的后几行不读入; by_index:表的索引(默认第一个sheet)
  11.                 返回表格中某一行作为key的字典列表,key为unicode类型
  12.                 校验:不能有重复的项,不能有空项
  13.     '''
  14.     def __init__(self,file_contents=None,file_name=None,col_n=1,del_n=0,by_index=0,):
  15.         self.file_name = file_name
  16.         self.file_contents = file_contents
  17.         self.col_n = col_n
  18.         self.del_n = del_n
  19.         self.by_index = by_index
  20.               
  21.     def __call__(self):
  22.         try:
  23.             data = xlrd.open_workbook(filename=self.file_name,file_contents=self.file_contents)
  24.         except Exception,e:
  25.             print str(e)
  26.             return None
  27.         col_n = self.col_n
  28.         del_n = self.del_n
  29.         by_index = self.by_index
  30.         table = data.sheets()[by_index]
  31.         nrows = table.nrows #行数
  32.         #ncols = table.ncols #列数
  33.         colnames =  table.row_values(col_n-1) #某一行数据做字典的key
  34.         #validate
  35.         if colnames:
  36.             repeat_colnames = set([str(i) for i in colnames if colnames.count(i)!=1])
  37.             for i in colnames:
  38.                 if not i:
  39.                     raise NameError('Null colname exist')
  40.             if repeat_colnames:
  41.                 alert_info = ';'.join(repeat_colnames)
  42.                 raise NameError('repeat colname exist : %s'%alert_info)
  43.         rsp =[]
  44.         for rownum in range(col_n,nrows-del_n):
  45.             row = table.row_values(rownum)
  46.             if row:
  47.                 app = {}
  48.                 for i in range(len(colnames)):
  49.                     app[colnames[i].strip()] = row[i]
  50.                 rsp.append(app)
  51.         return rsp

  52. class Export_Excel:   
  53.     '''返回导出excel二进制数据,sheet_name为sheet名,headings为第一行,data为第二行后,2个列表的内容一一对应'''
  54.     def __init__(self,headings,data,sheet_name='export_xls',file_name=None):
  55.         self.sheet_name = sheet_name
  56.         self.headings = headings
  57.         self.data = data
  58.         self.file_name = file_name
  59.    
  60.     def __call__(self):
  61.         book = xlwt.Workbook()
  62.         sheet = book.add_sheet(self.sheet_name)
  63.         rowx = 0
  64.         for colx, value in enumerate(self.headings):
  65.             sheet.write(rowx, colx, value)
  66.         sheet.set_panes_frozen(True) # frozen headings instead of split panes
  67.         sheet.set_horz_split_pos(rowx+1) # in general, freeze after last heading row
  68.         sheet.set_remove_splits(True) # if user does unfreeze, don't leave a split there
  69.         for row in self.data:
  70.             rowx += 1
  71.             for colx, value in enumerate(row):
  72.                 sheet.write(rowx, colx, value.encode('utf-8').decode('utf-8'))
  73.         buf = cStringIO.StringIO()
  74.         if self.file_name:
  75.             book.save(self.file_name)
  76.         book.save(buf)
  77.         out = base64.encodestring(buf.getvalue())
  78.         buf.close()
  79.         return out

  80. '''   
  81. ##test_for_use

  82. r = Read_Excel(file_contents=base64.decodestring(form['import']),col_n=3,del_n=1)
  83. trades = r()[:]
  84. print trades[0][u'收货人姓名']
  85. print len(tables)
  86. for row in tables:
  87.     print row
  88.     for i in row:
  89.         print i,row[i]
  90.         
  91. headings = [u'订单号',u'下单日期']
  92. values = [['12345','2012-12-12'],['12346','2012-12-12']]
  93. out = Export_Excel(headings,values)()
  94. _result_fields['data']['default'] = out
  95. '''
  96. '''
  97. from read_excel import Read_Excel
  98. print Read_Excel(file_name='a.xls')()
  99. [{'c_1':'a_1','c_2':'b_1'},{'c_1':'a_2','c_2':'b_2'}]
  100. '''
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|技术支持|开发手册|Odoo中文网-远鼎旗下odoo培训网站 ( 苏ICP备15039516号 )

GMT+8, 2024-5-7 18:15 , Processed in 0.010578 second(s), 9 queries , Xcache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表