Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • eLearning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Información
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Browse all Industries
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Services for Partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

File downloading as .doc instead of .xls

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
xls_reportsv15
2508 Vistas
Avatar
Vault Odoo

I have customized a new report in excel. In a wizard, after selecting the required fields, one button is given to print. That time one new file will be created and shows in a field. From there we can download it.

But after downloading the extension seems like .doc instead of .xls. In the linux system it's opening in the Excel but in the windows system it's showing error. Following is my code.

import xlwt
import base64
from io import BytesIO
from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError, Warning
from datetime import date

class ZambiaSalePurchaseReport(models.TransientModel):
_name = "zambia.sale.purchase.report"
_description = "Zambia Sale Purchase Report"

start_date = fields.Date(required=True)
end_date = fields.Date(required=True)
report_type = fields.Selection([('sale', 'Sale'), ('purchase', 'Purchase')], required=True)
tax_id = fields.Many2one('account.tax')
company_id = fields.Many2one('res.company', string='Company', required=True,
default=lambda self: self.env.company)
state = fields.Selection([('choose', 'choose'), ('get', 'get')],
default='choose')
file_name = fields.Binary('Tax Report', readonly=True)
summary_data = fields.Char('Name', size=256)

def print_xls_report(self):
report_type = {'sale':'Sale Report','purchase':'Purchase Report'}
if self.start_date > self.end_date:
raise UserError(_("Can not select start date greater than end date"))
file_name = report_type.get(self.report_type) +str(self.start_date)+'TO'+str(self.end_date)+'.xls'

workbook = xlwt.Workbook(encoding="UTF-8")
format0 = xlwt.easyxf(
'font:height 500,bold True;pattern: pattern solid, fore_colour gray25;align: horiz center; borders: top_color black, bottom_color black, right_color black, left_color black,\
left thin, right thin, top thin, bottom thin;')
formathead2 = xlwt.easyxf(
'font:height 250,bold True;pattern: pattern solid, fore_colour gray25;align: horiz center; borders: top_color black, bottom_color black, right_color black, left_color black,\
left thin, right thin, top thin, bottom thin;')
format1 = xlwt.easyxf('font:bold True;pattern: pattern solid, fore_colour gray25;align: horiz left; borders: top_color black, bottom_color black, right_color black, left_color black,\
left thin, right thin, top thin, bottom thin;')
format2 = xlwt.easyxf('font:bold True;align: horiz left')
format3 = xlwt.easyxf('align: horiz left; borders: top_color black, bottom_color black, right_color black, left_color black,\
left thin, right thin, top thin, bottom thin;')

row, col = 8, 0
report_type = {'sale': 'Sale Report', 'purchase': 'Purchase Report'}
sheet = workbook.add_sheet(report_type.get(self.report_type))

sheet.col(0).width = int(30 * 260)
sheet.col(1).width = int(30 * 260)
sheet.col(2).width = int(30 * 260)
sheet.col(3).width = int(30 * 260)
sheet.col(4).width = int(50 * 260)
sheet.col(5).width = int(30 * 260)
sheet.col(6).width = int(30 * 260)
sheet.col(7).width = int(30 * 260)
sheet.col(8).width = int(30 * 260)

sheet.row(0).height_mismatch = True
sheet.row(0).height = 150 * 4

sheet.row(1).height_mismatch = True
sheet.row(1).height = 150 * 4

sheet.write_merge(0, 0, 0, 4, report_type.get(self.report_type), format0)
sheet.write_merge(1, 1, 0, 4, 'Start Date:' + str(self.start_date) + 'End Date:' + str(self.end_date), formathead2)

sheet.row(2).height_mismatch = True
sheet.row(2).height = 150 * 3

report_type = {'sale': 'Sale Report', 'purchase': 'Purchase Report'}

if self.report_type == 'sale':
order_ids = self.env['account.move'].search([
('invoice_date', '>=', self.start_date),
('invoice_date', '<=', self.end_date),
('company_id', '=', self.company_id.id),
('move_type', 'in', ['out_invoice', 'out_refund']),
('state', '=', 'posted')], order="id asc")

date = str(self.start_date) + ' - ' + str(self.end_date)
sheet.write(2, 0, 'TPIN of Purchaser', formathead2)
sheet.write(2, 1, 'Name Of Purchaser', formathead2)
sheet.write(2, 2, 'Invoice Number', formathead2)
sheet.write(2, 3, 'Invoice Date', formathead2)
sheet.write(2, 4, "Description Of Goods & Services", formathead2)
sheet.write(2, 5, "Amount Before Tax", formathead2)
sheet.write(2, 6, "Local Excise Duty", formathead2)
sheet.write(2, 7, "Total", formathead2)
sheet.write(2, 8, "Vat Charged", formathead2)

row = 3
for order_id in order_ids:
line_ids = order_id.invoice_line_ids
line_name = line_ids[0].name if line_ids else "--"
amount_without_tax, vat_charge, total_amount = 0, 0, 0
for line_id in line_ids:
if self.tax_id.id in line_id.tax_ids.ids:
if order_id.move_type == 'out_refund':
amount_without_tax += -(line_id.price_subtotal)
total_amount += -(line_id.price_total)
vat_charge += -(line_id.price_total - line_id.price_subtotal)
else:
amount_without_tax += line_id.price_subtotal
total_amount += line_id.price_total
vat_charge += line_id.price_total - line_id.price_subtotal

sheet.write(row, 0, order_id.partner_id.tpin if order_id.partner_id.tpin else '--')
sheet.write(row, 1, order_id.partner_id.name)
sheet.write(row, 2, order_id.name)
sheet.write(row, 3, str(order_id.invoice_date))
sheet.write(row, 4, line_name)
sheet.write(row, 5, amount_without_tax)
sheet.write(row, 6, 0)
sheet.write(row, 7, total_amount)
sheet.write(row, 8, vat_charge)
row += 1


elif self.report_type == 'purchase':
order_ids = self.env['account.move'].search([
('invoice_date', '>=', self.start_date),
('invoice_date', '<=', self.end_date),
('company_id', '=', self.company_id.id),
('move_type', 'in', ['in_invoice', 'in_refund']),
('state', '=', 'posted')], order="id asc")

date = str(self.start_date) + ' - ' + str(self.end_date)
sheet.write(2, 0, 'TPIN of Supplier', formathead2)
sheet.write(2, 1, 'Name Of Supplier', formathead2)
sheet.write(2, 2, 'Invoice Number', formathead2)
sheet.write(2, 3, 'Invoice Date', formathead2)
sheet.write(2, 4, "Description Of Goods & Services", formathead2)
sheet.write(2, 5, "Amount Before Tax", formathead2)
sheet.write(2, 6, "Vat Charged", formathead2)

row = 3
for order_id in order_ids:
line_ids = order_id.invoice_line_ids
line_name = line_ids[0].name if line_ids else "--"
amount_without_tax, vat_charge, total_amount = 0, 0, 0
for line_id in line_ids:
if self.tax_id.id in line_id.tax_ids.ids:
if order_id.move_type == 'in_refund':
amount_without_tax += -(line_id.price_subtotal)
total_amount += -(line_id.price_total)
vat_charge += -(line_id.price_total - line_id.price_subtotal)
else:
amount_without_tax += line_id.price_subtotal
total_amount += line_id.price_total
vat_charge += line_id.price_total - line_id.price_subtotal
sheet.write(row, 0, order_id.partner_id.tpin if order_id.partner_id.tpin else '--')
sheet.write(row, 1, order_id.partner_id.name)
sheet.write(row, 2, order_id.name)
sheet.write(row, 3, str(order_id.invoice_date))
sheet.write(row, 4, line_name)
sheet.write(row, 5, amount_without_tax)
sheet.write(row, 6, vat_charge)
row += 1
fp = BytesIO()
workbook.save(fp)
self.write(
{'state': 'get', 'file_name': base64.encodestring(fp.getvalue()), 'summary_data': file_name})
fp.close()
return {
'type': 'ir.actions.act_window',
'res_model': 'zambia.sale.purchase.report',
'view_mode': 'form',
'view_type': 'form',
'res_id': self.id,
'target': 'new',
}
# return res

@api.onchange('report_type')
def onchange_basket(self):
for rec in self:
rec.tax_id = False
res = {
'domain' : {
'tax_id' : [('type_tax_use', '=', self.report_type)],
},
}
return res

0
Avatar
Descartar
Milin Prajapati

Consider using xlsxwriter module of python

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Prevent navigation if records are not save
v15
Avatar
Avatar
Avatar
2
oct 25
3113
Creating user creates duplicated partner_id
v15
Avatar
Avatar
1
sept 25
3036
Sales order line comment to Purchase order line comment Resuelto
v15
Avatar
Avatar
3
jul 25
4347
attribute is not applied when dynamically rendering
v15
Avatar
1
may 25
2455
Odoo Custome Module Language Creation
v15
Avatar
Avatar
Avatar
Avatar
4
may 25
3869
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

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