import { AfterViewInit, Component, OnDestroy, OnInit } from ‘@angular/core’; import {…
- User
import { AfterViewInit, Component, OnDestroy, OnInit } from ‘@angular/core’; import { AlmacenService } from ‘…/…/almacen/services/almacen.service’; import { Config } from ‘datatables.net’; import { ADTSettings } from ‘angular-datatables/src/models/settings’; import { Subject } from ‘rxjs’; import { Almacen } from ‘…/…/models/almacen.model’;
@Component({ selector: ‘app-inventario-almacen’, templateUrl: ‘./inventario-almacen.component.html’, styleUrl: ‘./inventario-almacen.component.css’ }) export class InventarioAlmacenComponent implements AfterViewInit, OnInit, OnDestroy {
dtOptions: Config = {}; dtTrigger = new Subject(); detalleSeccion: Record<string, any>[] = []; almacenes: Almacen[] = []; idalmacen: number | null = null; iconClass: string = ‘’;
constructor(private almacenService: AlmacenService) {}
ngOnInit(): void { this.configDataTable(); this.listarAlmacenes(); }
ngAfterViewInit(): void { this.initDataTable(); setTimeout(() => { this.dtTrigger.next(this.dtOptions); }, 200); }
configDataTable(): void { this.dtOptions = { language: { url: ‘https://cdn.datatables.net/plug-ins/2.0.8/i18n/es-ES.json’, paginate: { first: ‘<i class=“bi bi-chevron-double-left”>’, last: ‘<i class=“bi bi-chevron-double-right”>’, next: ‘<i class=“bi bi-chevron-right”>’, previous: ‘<i class=“bi bi-chevron-left”>’, }, },
responsive: true, columnDefs: [ { responsivePriority: 1, targets: -1 }, { responsivePriority: 2, targets: 1 }, ],
layout: { top2Start: ‘buttons’, topStart: ‘pageLength’, topEnd: ‘search’, },
buttons: { dom: { button: { tag: ‘button’, className: ‘btn’, }, }, buttons: [ { extend: ‘excelHtml5’, className: ‘btn btn-outline-success’, text: ‘<i class=“bi bi-file-earmark-excel”>’, titleAttr: ‘Excel’, }, { extend: ‘pdfHtml5’, className: ‘btn btn-outline-danger’, text: ‘<i class=“bi bi-file-earmark-pdf”>’, titleAttr: ‘PDF’, }, ], }, }; }
initDataTable(): void { const that = this; this.dtOptions = { …this.dtOptions, ajax: (dataTablesParameters: any, callback) => { this.listar(callback); },
columns: [ { title: ‘ID’, data: ‘idproducto’ }, { title: ‘Descripcion’, data: ‘nombre_producto’ }, { title: ‘Seccion’, data: ‘nombre_categoria’ }, { title: ‘Capacidad’, data: ‘stock’ }, ], }; }
listarAlmacenes(): void { this.almacenService.listarAlmacenes().subscribe({ next: (almacenes) => { this.almacenes = almacenes; this.idalmacen = this.almacenes[0].idalmacen; this.obtenerDetallesSeccion(this.idalmacen) }, error: (error) => { console.error(‘Error al obtener almacenes’, error); }, }); }
obtenerDetallesSeccion(idalmacen: number): void { this.almacenService.obtenerDetalleSeccion(idalmacen).subscribe({ next: (detalles: Record<string, any>[]) => { this.detalleSeccion = detalles; }, error: (error) => { console.error(‘Error al obtener detalles de la sección’, error); }, }); }
alertClass(cantProd: number, capdAlmc: number): string { const espacio = cantProd / capdAlmc; if (espacio < 0.6) { this.iconClass = ‘bi-check-circle-fill’; return ‘alert-success’; } else if (espacio < 0.85) { this.iconClass = ‘bi-exclamation-triangle-fill’; return ‘alert-warning’; } else { this.iconClass = ‘bi-exclamation-octagon-fill’; return ‘alert-danger’; } }
listar(callback: any): void { this.almacenService.listarProductosPorAlmacen(this.idalmacen!).subscribe({ next: (almacenes: Record<string, any>[]) => { callback({ data: almacenes, }); }, error: (error) => { console.error(‘Error a listar almacén’, error); }, }); }
filtrarProductosPorAlmacen(id: number): void { this.idalmacen = id; this.obtenerDetallesSeccion(this.idalmacen); this.refreshTable(); }
refreshTable() { const tabla = $(‘#tablaInventarioAlmacen’).DataTable(); if (tabla) { tabla.ajax.reload(); } }
ngOnDestroy(): void { this.dtTrigger.unsubscribe(); }
}
- tengo este componente en angular y lleno un listado con ajax datatble, quiero saber si hay una forma de qeu al momento de imporimir en excel o pdf tome este div - Almacén
- Assistant
Sí, puedes lograr que el contenido del
div<h2>Almacén</h2>y otros elementos se incluyan en el archivo Excel o PDF con DataTables utilizando las opciones avanzadas de personalización que ofrecen las libreríasexcelHtml5ypdfHtml5. Puedes hacerlo de la siguiente manera:- Añadir el título "Almacén" y otras informaciones manualmente.
- Modificar la configuración de los botones para incluir encabezados personalizados.
Aquí te dejo un ejemplo de cómo podrías modificar la configuración de los botones para incluir el título y otros detalles en los archivos exportados:
import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core'; import { AlmacenService } from '../../almacen/services/almacen.service'; import { Config } from 'datatables.net'; import { ADTSettings } from 'angular-datatables/src/models/settings'; import { Subject } from 'rxjs'; import { Almacen } from '../../models/almacen.model'; @Component({ selector: 'app-inventario-almacen', templateUrl: './inventario-almacen.component.html', styleUrls: ['./inventario-almacen.component.css'] }) export class InventarioAlmacenComponent implements AfterViewInit, OnInit, OnDestroy { dtOptions: Config = {}; dtTrigger = new Subject<ADTSettings>(); detalleSeccion: Record<string, any>[] = []; almacenes: Almacen[] = []; idalmacen: number | null = null; iconClass: string = ''; titulo: string = 'Almacén'; constructor(private almacenService: AlmacenService) {} ngOnInit(): void { this.configDataTable(); this.listarAlmacenes(); } ngAfterViewInit(): void { this.initDataTable(); setTimeout(() => { this.dtTrigger.next(this.dtOptions); }, 200); } configDataTable(): void { this.dtOptions = { language: { url: 'https://cdn.datatables.net/plug-ins/2.0.8/i18n/es-ES.json', paginate: { first: '<i class="bi bi-chevron-double-left"></i>', last: '<i class="bi bi-chevron-double-right"></i>', next: '<i class="bi bi-chevron-right"></i>', previous: '<i class="bi bi-chevron-left"></i>', }, }, responsive: true, columnDefs: [ { responsivePriority: 1, targets: -1 }, { responsivePriority: 2, targets: 1 }, ], layout: { top2Start: 'buttons', topStart: 'pageLength', topEnd: 'search', }, buttons: { dom: { button: { tag: 'button', className: 'btn', }, }, buttons: [ { extend: 'excelHtml5', className: 'btn btn-outline-success', text: '<i class="bi bi-file-earmark-excel"></i>', titleAttr: 'Excel', title: this.titulo, customize: (xlsx) => { const sheet = xlsx.xl.worksheets['sheet1.xml']; const numRows = $('row', sheet).length; const additionalRow = '<row r="1">' + '<c t="inlineStr" r="A1">' + '<is><t>' + this.titulo + '</t></is>' + '</c>' + '</row>'; // Insert additional rows before the existing rows $('sheetData', sheet).prepend(additionalRow); } }, { extend: 'pdfHtml5', className: 'btn btn-outline-danger', text: '<i class="bi bi-file-earmark-pdf"></i>', titleAttr: 'PDF', title: this.titulo, customize: (doc) => { doc.content.splice(0, 0, { text: this.titulo, margin: [0, 0, 0, 12], fontSize: 18 }); } }, ], }, }; } initDataTable(): void { const that = this; this.dtOptions = { ...this.dtOptions, ajax: (dataTablesParameters: any, callback) => { this.listar(callback); }, columns: [ { title: 'ID', data: 'idproducto' }, { title: 'Descripcion', data: 'nombre_producto' }, { title: 'Seccion', data: 'nombre_categoria' }, { title: 'Capacidad', data: 'stock' }, ], }; } listarAlmacenes(): void { this.almacenService.listarAlmacenes().subscribe({ next: (almacenes) => { this.almacenes = almacenes; this.idalmacen = this.almacenes[0].idalmacen; this.obtenerDetallesSeccion(this.idalmacen) }, error: (error) => { console.error('Error al obtener almacenes', error); }, }); } obtenerDetallesSeccion(idalmacen: number): void { this.almacenService.obtenerDetalleSeccion(idalmacen).subscribe({ next: (detalles: Record<string, any>[]) => { this.detalleSeccion = detalles; }, error: (error) => { console.error('Error al obtener detalles de la sección', error); }, }); } alertClass(cantProd: number, capdAlmc: number): string { const espacio = cantProd / capdAlmc; if (espacio < 0.6) { this.iconClass = 'bi-check-circle-fill'; return 'alert-success'; } else if (espacio < 0.85) { this.iconClass = 'bi-exclamation-triangle-fill'; return 'alert-warning'; } else { this.iconClass = 'bi-exclamation-octagon-fill'; return 'alert-danger'; } } listar(callback: any): void { this.almacenService.listarProductosPorAlmacen(this.idalmacen!).subscribe({ next: (almacenes: Record<string, any>[]) => { callback({ data: almacenes, }); }, error: (error) => { console.error('Error a listar almacén', error); }, }); } filtrarProductosPorAlmacen(id: number): void { this.idalmacen = id; this.obtenerDetallesSeccion(this.idalmacen); this.refreshTable(); } refreshTable() { const tabla = SDOLAR('#tablaInventarioAlmacen').DataTable(); if (tabla) { tabla.ajax.reload(); } } ngOnDestroy(): void { this.dtTrigger.unsubscribe(); } }En este ejemplo, estamos utilizando las funciones
customizeintegradas enexcelHtml5ypdfHtml5. Esto nos permite inyectar el título y otros detalles que necesites en el archivo exportado utilizando la propiedadtitle.Además, recuerda que en el código HTML, tendrás que usar los atributos
[title]y[titleAttr]correspondientes para asegurarte de que los títulos sean dinámicos y se actualicen correctamente.<!-- inventario-almacen.component.html --> <h2>Almacén</h2> <div class="mt-3"> <div class="btn-group" role="group" aria-label="Almacenes"> <button *ngFor="let almacen of almacenes" class="btn btn-primary" [id]="almacen.idalmacen" (click)="filtrarProductosPorAlmacen(almacen.idalmacen)" type="button"> {{ almacen.seccion }} </button> </div> </div> <div *ngIf="detalleSeccion" class="mt-3"> <div *ngFor="let det of detalleSeccion" [ngClass]="alertClass(det['cantidad_producto'], det['capacidad'])" class="alert d-flex align-items-center justify-content-between" role="alert"> <div> <p><strong>ID Almacén: </strong> {{ det['idalmacen'] }}</p> <p><strong>Descripción: </strong> {{ det['descripcion'] }}</p> <p><strong>Sección: </strong> {{ det['seccion'] }}</p> <p><strong>Capacidad: </strong> {{ det['capacidad'] }}</p> <p><strong>Cantidad de productos: </strong> {{ det['cantidad_producto'] }}</p> <p><strong>{{ det['espacio_disponible'] }}</strong></p> </div> <i [ngClass]="iconClass" class="bi flex-shrink-0 ms-2" style="font-size: 24px;"></i> </div> </div> <table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" id="tablaInventarioAlmacen" class="table table-hover w-100 nowrap" [cellSpacing]="0" [width]="100%"> <thead class="table-dark"> </thead> </table>Ahora, cada vez que exportes los datos a Excel o PDF utilizando los botones de DataTables, se incluirá el título personalizado "Almacén" en el archivo exportado. Puedes modificar el contenido de
customizepara incluir otros detalles según tus necesidades.