Перейти к содержимому
Odoo Меню
  • Войти
  • Попробовать бесплатно
  • Модули
    Финансы
    • Бухгалтерия
    • Выставление счетов
    • Расходы
    • Таблицы
    • Документооборот
    • Подпись
    Продажи
    • CRM
    • Продажи
    • POS Магазин
    • POS Ресторан
    • Подписки
    • Аренда
    Вебсайты
    • Конструктор вебсайтов
    • eCommerce
    • Блог
    • Форум
    • Онлайн-чат
    • Электронное обучение
    Логистика
    • Склад
    • Производство
    • PLM
    • Закупки
    • Обслуживание
    • Качество
    Отдел кадров
    • Сотрудники
    • Подбор персонала
    • Отпуска
    • Оценка персонала
    • Реферальная программа
    • Автопарк
    Маркетинг
    • SMM
    • E-mail рассылки
    • СМС рассылки
    • Мероприятия
    • Автоматизация маркетинга
    • Опросы
    Услуги
    • Проекты
    • Табели
    • Выездной сервис
    • Поддержка
    • Планирование
    • Встречи
    Продуктивность
    • Обсуждения
    • Согласование
    • IoT
    • VoIP-телефония
    • Knowledge
    • WhatsApp
    Сторонние приложения Модуль Студия Odoo Платформа Odoo Cloud
  • Индустрии
    Розничная торговля
    • Книжный магазин
    • Магазин одежды
    • Мебельный магазин
    • Продуктовый магазин
    • Строительный магазин
    • Магазин игрушек
    Гостинично-ресторанный бизнес
    • Бар и паб
    • Ресторан
    • Фастфуд
    • Гостевой дом
    • Дистрибьютор напитков
    • Отель
    Недвижимость
    • Агентство недвижимости
    • Архитектурное бюро
    • Строительство
    • Управление недвижимостью
    • Ландшафтный дизайн
    • Товарищество собственников жилья
    Консалтинг
    • Бухгалтерская фирма
    • Партнер Odoo
    • Маркетинговое агентство
    • Юридическая фирма
    • Подбор персонала
    • Аудиторское бюро
    Производство
    • Текстиль
    • Металл
    • Мебель
    • Продукты питания
    • Пивоварня
    • Корпоративные сувениры
    Здоровье и фитнес
    • Спортивный комплекс
    • Магазин оптики
    • Фитнес-клуб
    • Велнес-центр
    • Аптека
    • Салон красоты
    Услуги
    • Специалист по бытовым услугам
    • Продажа и обслуживание IT-оборудования
    • Солнечные энергосистемы
    • Производство обуви
    • Клининг
    • Системы ОВКВ
    Прочее
    • Некоммерческая организация
    • Консалтинг в сфере устойчивого развития
    • Аренда рекламных щитов
    • Бизнес по фотосъемке
    • Прокат велосипедов
    • Реселлер программного обеспечения
    Все индустрии
  • Community
    Обучение
    • Видео уроки
    • Документация
    • Сертификация
    • Тренинг
    • Блог
    • Подкаст
    Образование и развитие
    • Образовательная программа
    • Деловая игра Scale Up!
    • Экскурсия в офис Odoo
    ПО
    • Скачать
    • Сравнить версии
    • Релизы
    Сотрудничество
    • Github
    • Форум
    • Мероприятия
    • Перевод
    • Стать партнером
    • Услуги для партнеров
    • Зарегистрировать бухгалтерскую фирму
    Услуги
    • Найти партнера
    • Найти бухгалтера
    • Встреча с экспертом
    • Услуги по внедрению
    • Отзывы клиентов
    • Поддержка
    • Обновления
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Заказать демонстрацию
  • Цены
  • Поддержка

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухгалтерия
  • Склад
  • PoS
  • Проекты
  • MRP
All apps
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Помощь

generate xls or csv file

Подписаться

Получайте уведомления о появлении активности в этом посте

Этот вопрос был отмечен
csvxlsodoo8.0
1 Ответить
9843 Представления
Аватар
Abderrahmen

Plz i need to know how can i generate xls or csv file filled with data for exemple an array. Thank you.

0
Аватар
Отменить
OdooBot
Thank you friend,
the thing is, creating a file is not a problem but my probleme that i want to generate a file after click event in a button to show the save file window. 

2015-11-19 19:45 GMT+01:00 Drees Far <far.drees@gmail.com>:

A new answer for generate xls or csv file has been posted. Click here to access the post.

--
Drees Far
Sent by Odoo S.A. using Odoo about Forum Post generate xls or csv file



--

 

Abderrahmen KHALLEDI
Développeur Odoo/OpenERP
Villa n°5, rue Haroun El Rachid Mutuelle ville
Tél. : +216 55 521 232
Mail : abderrahmen@techcare.tn
Linkedin : tn.linkedin.com/in/abderrahmenkhalledi/
Site : http://www.techcare-group.tn

Аватар
Rihene
Лучший ответ

Hello my friend;

here is some useful links that can help you a lot:

http://stackoverflow.com/questions/2084069/create-a-csv-file-with-values-from-a-python-list

http://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file

http://gis.stackexchange.com/questions/72458/export-list-of-values-into-csv-or-txt-file

https://docs.python.org/2/library/csv.html

You can use the ir.attachment module. I fact, you will create a .csv file in your pc and then a button which will call a function that you define in you python.And here is an example:

def print_declaration(self, cr, uid, ids, id, context=None):

print ids

dec = self.pool.get('declaration.cnss')

obj = dec.search(cr, uid, [('id','in', ids)])

cns = dec.read(cr, uid, obj, ['id', 'year','trimester','company_id'], context=False)

year = cns[0]['year']

company = cns[0]['company_id'][0]

print company

trimester = cns[0]['trimester']

filename="/opt/file.txt"

lines = open(filename).readlines()  

open(filename, 'w').writelines(lines[-1:-1])

writepath = '/opt/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w' 

var = 0

i = 0

j = 0

page =1

res_list=[]

payslip_line = self.pool.get('hr.payslip')

obj_ids = payslip_line.search(cr, uid, [('company_id','=', company)]) 

for res in payslip_line.read(cr, uid, obj_ids, ['id', 'employee_id','date_from'], context=False):

date = res['date_from']

var = var + 1

if var == 12:

var = 1

obj = {}

obj['matricule'] = res['employee_id'][0]

a = str(obj['matricule'])

obj['numero'] = var

matricule = res['employee_id'][0]

obj['name'] = res['employee_id'][1]

payslip_lines = self.pool.get('hr.employee')

obj_ids2 = payslip_lines.search(cr, uid, [('id', '=', matricule)])

for res in payslip_lines.read(cr, uid, obj_ids2, ['id', 'n_cnss', 'momo_category','address_id','name_employee','surname_emloyee','name_fother','marital','gender','nic_id'], context=False):

marital = res['marital']

gender = res['gender']

nom_employe = res['name_employee']

prenom_employe = res['surname_emloyee']

nom_pere = res['name_fother']

if nom_employe== False:

My_error_Msg = 'Please, enter the name of your employee'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

if prenom_employe== False:

My_error_Msg = 'Please, enter the surname of your employee'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

if nom_pere== False:

My_error_Msg = 'Please, enter the surname of your Employee Fother'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

nom = prenom_employe+''+nom_employe

if gender=='male':

nom = prenom_employe+' B '+nom_pere+ ' ' +nom_employe

if gender=='female' and marital=='single':

nom = prenom_employe+' BT '+nom_pere+ ' ' +nom_employe

if gender=='female' and marital=='married':

nom = prenom_employe+ ' ' +nom_employe

if gender=='female' and marital=='widower':

nom = prenom_employe+' BT '+nom_pere+ ' ' +nom_employe

if gender=='female' and marital=='divorced':

nom = prenom_employe+' BT '+nom_pere+ ' ' +nom_employe

company = self.pool.get('res.partner')

company_ids = company.search(cr, uid, [('id','=',res['address_id'][0])]) 

for test in company.read(cr, uid, company_ids, ['id', 'company_id'], context=False):

companys = self.pool.get('res.company')

companys_ids = companys.search(cr, uid, [('id','=',test['company_id'][0])])

for tests in companys.read(cr, uid, company_ids, ['id', 'cnss'], context=False):

j = j + 1

if j %12==0:

page = page +1

c = str(0)

d = str(page)

pages = c+c+d

var1 = map(int, str(tests['cnss']))

var2 = var1[-1]

var3 = var1[-2]

var4 = int(str(var3) + str(var2))

var5 = var1.remove(var2)

var6 = var1.remove(var3)

s = map(str, var1)

s = ''.join(s)

s = int(s)

obj['matricule_employeur'] = s

obj['cle_employeur'] = var4

test = str(var4)

test2 = str(s)

test2 = '00'+test2

if len (test2) <> 8:

My_error_Msg = 'Taille de la matricule CNSS non compatible'

raise osv.except_osv(_("Erreur!"), _(My_error_Msg))

return False

taux_cotisation = str(0000)

variable1 = map(int, str(res['n_cnss']))

variable2 = variable1[-1]

variable3 = variable1[-2]

variable4 = int(str(variable3) + str(variable2))

cle_assure = variable4

variable5 = variable1.remove(variable2)

variable6 = variable1.remove(variable3)

matricule_assure = map(str, variable1)

matricule_assure = ''.join(matricule_assure)

if len (matricule_assure) <> 8:

My_error_Msg = 'Taille du numero Assure social non compatible'

raise osv.except_osv(_("Erreur!"), _(My_error_Msg))

return False

matricules_assure = str(matricule_assure)

cles_assure = str(cle_assure)

print ('---------------------------en test--------------------------------')

marital = res['marital']

gender = res['gender']

nom_employe = res['name_employee']

prenom_employe = res['surname_emloyee']

nom_pere = res['name_fother']

if nom_employe== False:

My_error_Msg = 'Please, enter the name of your employee'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

if prenom_employe== False:

My_error_Msg = 'Please, enter the surname of your employee'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

if nom_pere== False:

My_error_Msg = 'Please, enter the surname of your Employee Fother'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

nom = prenom_employe+''+nom_employe

if gender=='male':

nom = prenom_employe+' B '+nom_pere+ ' ' +nom_employe

if gender=='female' and marital=='single':

nom = prenom_employe+' BT '+nom_pere+ ' ' +nom_employe

if gender=='female' and marital=='married':

nom = prenom_employe+ ' ' +nom_employe

if gender=='female' and marital=='widower':

nom = prenom_employe+' BT '+nom_pere+ ' ' +nom_employe

if gender=='female' and marital=='divorced':

nom = prenom_employe+' BT '+nom_pere+ ' ' +nom_employe

if len(nom) > 60:

My_error_Msg = 'Please, The size of your employee name is incorrect'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

num_cin = res['nic_id']

cin = str(num_cin)

if num_cin ==False:

My_error_Msg = 'Please, enter the CIN of your employee'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

if len(cin) > 8:

My_error_Msg = 'Please, the size of the CIN of your employee is incorrect'

raise osv.except_osv(_("Error!"), _(My_error_Msg))

return False

taille_nom = len(nom)

nbr_espace = 60 - taille_nom

for i in range (nbr_espace):

nom = nom+' '

if taille_nom < 60:

nom = nom+''

brut_line = self.pool.get('declaration.cnss.line')

brut_ids= brut_line.search(cr, uid, [])

somme_brut1 = 0

somme_brut2 = 0

somme_brut3 = 0

for res in brut_line.read(cr, uid, brut_ids, ['id', 'brut','brut2','brut3'], context=False):

obj['brut'] = res['brut']

obj['brut2'] = res['brut2']

obj['brut3'] = res['brut3']

somme_brut1 = somme_brut1 + res['brut']

somme_brut2 = somme_brut2 + res['brut2']

somme_brut3 = somme_brut3 + res['brut3']

somme = res['brut'] + res['brut2'] + res['brut3']

somme_brut = somme_brut1 + somme_brut2 + somme_brut3

sommes = 1000*somme

obj['somme_brut1'] = somme_brut1

obj['somme_brut2'] = somme_brut2

obj['somme_brut3'] = somme_brut3

obj['somme_brut'] = somme_brut

obj['somme'] = sommes

salaire = str(int(sommes))

nbr_espace2 = 10 - len (salaire)

j = 0

for j in range (nbr_espace2):

salaire = '0'+salaire

a = str(var)

b = str(0)

ligne = b+a

print len (test2+test+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+trimester+year+pages+ligne+matricules_assure+cles_assure+nom+cin+salaire+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation)

with open(writepath, mode) as f:

f.write(test2+test+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+trimester+year+pages+ligne+matricules_assure+cles_assure+nom+cin+salaire+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+taux_cotisation+'\n')

res_list.append(obj)

filename="/opt/file.txt"

files = open(filename,'rb').read()

point = "."

nom_fichier = "DS"+test2+test+taux_cotisation+taux_cotisation+taux_cotisation+str(6)+point+trimester+year

files = open(filename,'rb').read().encode('base64')

ir_values={

'name': nom_fichier,

'datas_fname': nom_fichier,

'type': 'binary',

'datas': files,

'create_uid': uid,

# 'partner_id': ids[0],

'res_model': 'declaration.cnss',

'res_id': ids[0],

} 

self.pool.get('ir.attachment').create(cr,uid,ir_values,context=context)

here is an example that i have wirked with but a text file and i am certain that it will work with the csv

Best Regards.

1
Аватар
Отменить
Abderrahmen
Автор

Thank you my friend, the thing is, creating a file is not a problem but my probleme that i want to generate a file after click event in a button to show the save file window.

Rihene

its an example of a file that i have created and it works perfectly :) plz vote and upvote ;)

Не оставайтесь в стороне – присоединяйтесь к обсуждению!

Создайте аккаунт сегодня, чтобы получить доступ к эксклюзивным функциям и стать частью нашего замечательного сообщества!

Регистрация
Похожие посты Ответы Просмотры Активность
customization on base export functionality
export csv xls
Аватар
0
сент. 18
4570
TypeError: error.data.arguments is undefined
csv typeerror odoo8.0 importing data from excel file
Аватар
0
янв. 17
5873
Custom Import method - how to ?
import csv order.lines odoo8.0
Аватар
Аватар
2
февр. 16
8695
how to implement joint piece in odoo 8 in one view
odoo8.0
Аватар
0
апр. 24
2582
what is the reason behind extra move? in stock
odoo8.0
Аватар
Аватар
Аватар
Аватар
4
нояб. 23
6732
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • Github
  • Runbot
  • Перевод
Услуги
  • Хостинг Odoo.sh
  • Поддержка
  • Обновление
  • Индивидуальные решения по доработке
  • Образование
  • Найти бухгалтера
  • Найти партнера
  • Стать партнером
О нас
  • Наша компания
  • Активы бренда
  • Cвяжитесь с нами
  • Вакансии
  • Мероприятия
  • Подкаст
  • Блог
  • Клиенты
  • Правовые документы • Конфиденциальность
  • Безопасность
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo – это набор бизнес-модулей с открытым исходным кодом, который закроет все потребности вашей компании: CRM, E-commerce, Бухгалтерия, Склад, POS, управление проектами и др.

Odoo сочетает в себе простоту использования и полную интеграцию всех бизнес-процессов в одной системе.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now