Skip to content

Instantly share code, notes, and snippets.

@WorldException
Created September 30, 2015 07:06
Show Gist options
  • Save WorldException/cdfce52e9da29437d724 to your computer and use it in GitHub Desktop.
Save WorldException/cdfce52e9da29437d724 to your computer and use it in GitHub Desktop.
#!python
#-*-coding:utf8-*-
'''
Стоянов Евгений [email protected]
Модуль для формирования внутреннего представления типов 1С 7.7, которые можно восстановить с помощью методов ЗначениеИзСтроки()
ТаблицаЗначений
{"ТаблицаЗначений","2",{"0","","0","0","0","","2",{{"Кол1","Кол1","1","0","0",{"Строка",""},"","0",{{"Строка","тест"}}},{"Кол2","Кол2","1","0","1",{"Строка",""},"","0",{{"Строка","1231"}}}}}}
'''
import copy
def v7table_to_dict(tb):
'''
преобразует таблицу в список кортежей
@param tb: таблица значений в представлении питона [[col,col],[val,val],[val,val]]
@return: [{'col':val,'col':'val'},]
'''
keys=tb[0]
lines=[]
for line in tb[1:]:
valuedict={}
for i,key in enumerate(keys):
valuedict[key]=line[i]
lines.append(valuedict)
return lines
def dict_to_v7table(dc):
tb=[]
if not dc:
return tb
keys=dc[0].keys()
tb.append(keys)
for item in dc:
line=[]
for key in keys:
line.append(item[key])
tb.append(line)
return tb
class V7Table:
def __init__(self,_columns=[]):
self.columns = copy.copy(_columns)
self.lines=u''
self.head = u''
self.lineno=0
if type(self.columns) in (list,tuple):
self.column_names = self.columns
elif type(self.columns) == dict:
self.column_names = self.columns.keys()
self.col_values = ['' for i in range( self.ncols() )]
for n in range(0,self.ncols()):
#self.col_values = u'{"%(cname)s","%(cname)s","1","0","%(cnum)s",{"Строка",""},"","0",{%(lines)s}},\n' % {'cname':self.column_names[n], 'cnum':(n)}
self.col_values[n] = u'{"%(cname)s","%(cname)s","1","0","%(cnum)s",{"Строка",""},"","0",{' % {'cname':self.column_names[n], 'cnum':(n)}
self.__v8_makeheader__()
def add(self,line):
'''
line = {'col':val} or ['val1','val2']
'''
self.lines += self.__v8_makerow__(line)
def append_all(self,_list_of_dict):
for item in _list_of_dict:
if item.__class__==dict:
self.add(item.values())
elif item.__class__ in (list,tuple):
self.add(item)
def ncols(self):
return len(self.columns)
def save(self,filename):
pass
def __v8_makeheader__(self):
self.head = u'{"ТаблицаЗначений","%(ncols)s",{"0","","0","0","0","","%(ncols)s",{' % {'ncols':self.ncols()}
return self.head
def __v8_makerow__(self,row):
#{"Кол1","Кол1","1","0","0",{"Строка",""},"","0",{{"Строка","тест"}}} одна колонка
if len(row)>len(self.columns):
return ''
line = ''
colNo = 0
for value in row:
if value is None:
value=''
value_ = ('%s'%value).replace('"','""')
if value_.endswith('.0'):
value_ = value_[:-2]
#print colNo
#column = self.column_names[colNo]
self.col_values[colNo] += u'{"Строка","%(value)s"},\n' % {'value':value_}
#line += u'{"%(cname)s","%(cname)s","1","0","%(cnum)s",{"Строка",""},"","0",{{"Строка","%(value)s"}}},\n' % {'cname':column, 'cnum':(colNo), 'value':value_}
colNo += 1
self.lineno +=1
return line[:-1]
def export(self):
'''
возращает структуру пригодную для загрузки в 1С в качетсве таблицы значений
'''
self.txt = self.head
for i in range(0,self.ncols()):
if self.col_values[i].endswith(','):
self.txt += self.col_values[i][:-1] + u'}},'
else:
self.txt += self.col_values[i] + u'}},'
self.txt = self.txt[:-1] + u'}}}'
return self.txt
@staticmethod
def dumps(table):
if table:
v=V7Table(table[0])
v.append_all(table[1:])
return v.export()
return ''
@staticmethod
def loads(v7str):
'''
преобразует внутреннее представление таблицы 1С в массив, первой строкой идет
наименование колонок
'''
import json
#{"ТаблицаЗначений","2",{"0","","0","0","0","","2",{{"Кол1","Кол1","1","0","0",{"Строка",""},"","0",{{"Строка","тест"}}},{"Кол2","Кол2","1","0","1",{"Строка",""},"","0",{{"Строка","1231"}}}}}}
v7data=copy.copy(v7str)
v7data=v7data.replace('{','[')
v7data=v7data.replace('}',']')
d=json.loads(v7data)
#колонки
cols=[]
for line in d[2][7]:
cols.append(line[0])#.encode('cp1251'))
ncols=len(cols)
#Строки
data=[cols]
nrows=len(d[2][7][0][8]) # количество строк первой колонки
ncolsrange=range(0,ncols)
for r in range(0,nrows):
row=[]
for c in ncolsrange:
if d[2][7][c][8][r]:
row.append(d[2][7][c][8][r][1])#.encode('cp1251'))
else:
row.append('')
data.append(row)
return data
class vtable(list):
pass
def main():
v7 = V7Table([u'Кол1',u"Кол2"])
v7.add(['c1r1','c2r1'])
v7.add(['c1r2','c2r2'])
print v7.export().encode('cp1251')
v7 = V7Table([u'Кол1',u"Кол2"])
print v7.export().encode('cp1251')
print '='*10
t= u'{"ТаблицаЗначений","2",{"0","","0","0","0","","2",{{"name1","name1","1","0","0",{"Строка",""},"","0",{{"Строка","k11"},{"Строка","k12"}}},{"name2","name2","1","0","1",{"Строка",""},"","0",{{"Строка","k21"},{"Строка","k22"}}}}}}'
d= V7Table.loads(t)
print d
t2 = V7Table.dumps(d)
print t2.encode('cp1251').replace('\n','')
print t.encode('cp1251')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment