arreglos exportar a excel
se usa exceljs
This commit is contained in:
parent
a1ad7e0747
commit
b9b84a4d13
721
package-lock.json
generated
721
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -20,6 +20,7 @@
|
|||||||
"@fortawesome/fontawesome-free": "^6.7.2",
|
"@fortawesome/fontawesome-free": "^6.7.2",
|
||||||
"@primeng/themes": "^19.1.0",
|
"@primeng/themes": "^19.1.0",
|
||||||
"animate.css": "^4.1.1",
|
"animate.css": "^4.1.1",
|
||||||
|
"exceljs": "^4.4.0",
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"primeflex": "^4.0.0",
|
"primeflex": "^4.0.0",
|
||||||
"primeicons": "^7.0.0",
|
"primeicons": "^7.0.0",
|
||||||
|
|||||||
@ -32,7 +32,7 @@
|
|||||||
<div class="font-bold tituloTabla">Título de la tabla:</div>
|
<div class="font-bold tituloTabla">Título de la tabla:</div>
|
||||||
<p-button
|
<p-button
|
||||||
icon="pi pi-file-excel"
|
icon="pi pi-file-excel"
|
||||||
(onClick)="exportExcel(dt)"
|
(onClick)="exportExcelWithStyles(dt)"
|
||||||
styleClass="p-button-success"
|
styleClass="p-button-success"
|
||||||
pTooltip="Descargar planilla Excel"
|
pTooltip="Descargar planilla Excel"
|
||||||
tooltipPosition="top"
|
tooltipPosition="top"
|
||||||
@ -133,7 +133,7 @@
|
|||||||
pButton
|
pButton
|
||||||
type="button"
|
type="button"
|
||||||
icon="pi pi-file-excel"
|
icon="pi pi-file-excel"
|
||||||
(click)="exportExcel(dt)"
|
(click)="exportExcelWithStyles(dt)"
|
||||||
class="p-button-success"
|
class="p-button-success"
|
||||||
label="Exportar a Excel"
|
label="Exportar a Excel"
|
||||||
pTooltip="Descargar planilla Excel"
|
pTooltip="Descargar planilla Excel"
|
||||||
|
|||||||
@ -6,18 +6,17 @@ import { SelectModule } from 'primeng/select';
|
|||||||
import { ButtonModule } from 'primeng/button';
|
import { ButtonModule } from 'primeng/button';
|
||||||
import { TooltipModule } from 'primeng/tooltip';
|
import { TooltipModule } from 'primeng/tooltip';
|
||||||
import * as FileSaver from 'file-saver';
|
import * as FileSaver from 'file-saver';
|
||||||
import * as XLSX from 'xlsx';
|
import { Workbook } from 'exceljs';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-actualizacion-pd',
|
selector: 'app-actualizacion-pd',
|
||||||
imports: [
|
imports: [
|
||||||
FormsModule,
|
FormsModule,
|
||||||
TableModule,
|
TableModule,
|
||||||
InputTextModule,
|
InputTextModule,
|
||||||
SelectModule,
|
SelectModule,
|
||||||
ButtonModule,
|
ButtonModule,
|
||||||
TooltipModule
|
TooltipModule
|
||||||
|
|
||||||
],
|
],
|
||||||
templateUrl: './actualizacion-pd.component.html',
|
templateUrl: './actualizacion-pd.component.html',
|
||||||
styleUrl: './actualizacion-pd.component.scss',
|
styleUrl: './actualizacion-pd.component.scss',
|
||||||
@ -27,7 +26,7 @@ export class ActualizacionPdComponent {
|
|||||||
pageTitle: string = 'Cronogramas cargados:';
|
pageTitle: string = 'Cronogramas cargados:';
|
||||||
select1: any = '';
|
select1: any = '';
|
||||||
selectedCity: any = '';
|
selectedCity: any = '';
|
||||||
empresas: any[] = [{name: 'Empresa A'}, {name: 'Empresa B'}, {name: 'Empresa C'}];
|
empresas: any[] = [{ name: 'Empresa A' }, { name: 'Empresa B' }, { name: 'Empresa C' }];
|
||||||
estadoAprobacion = [
|
estadoAprobacion = [
|
||||||
{ name: 'Aprobado', value: 'Aprobado' },
|
{ name: 'Aprobado', value: 'Aprobado' },
|
||||||
{ name: 'Rechazado', value: 'Rechazado' },
|
{ name: 'Rechazado', value: 'Rechazado' },
|
||||||
@ -92,84 +91,110 @@ export class ActualizacionPdComponent {
|
|||||||
dato14: '',
|
dato14: '',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exporta la tabla a Excel
|
* Exporta la tabla a Excel usando ExcelJS
|
||||||
* @param table Referencia a la tabla PrimeNG
|
* @param table Referencia a la tabla PrimeNG
|
||||||
*/
|
*/
|
||||||
exportExcel(table: Table) {
|
|
||||||
// Preparamos los datos para exportar
|
|
||||||
const exportData = this.prepareDataForExport(table);
|
|
||||||
|
|
||||||
// Creamos el libro de Excel
|
|
||||||
const worksheet = XLSX.utils.json_to_sheet(exportData);
|
|
||||||
const workbook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
|
|
||||||
|
|
||||||
// Aplicamos estilos a las celdas (encabezados en negrita con fondo azul)
|
|
||||||
this.applyStyles(worksheet);
|
|
||||||
|
|
||||||
// Opciones de exportación
|
|
||||||
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
|
|
||||||
|
|
||||||
// Guardamos el archivo
|
|
||||||
this.saveAsExcelFile(excelBuffer, 'cronogramas_exportados');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
exportExcelWithStyles(table: Table): void {
|
||||||
* Prepara los datos para la exportación, filtrando según sea necesario
|
// Creamos un nuevo libro de trabajo
|
||||||
*/
|
const workbook = new Workbook();
|
||||||
prepareDataForExport(table: Table): any[] {
|
const worksheet = workbook.addWorksheet('Datos');
|
||||||
// Si hay filtros aplicados, usamos los datos filtrados
|
|
||||||
const data = table.filteredValue || table.value;
|
// Exportamos los datos y aplicamos estilos
|
||||||
|
this.addDataToWorksheet(worksheet, table);
|
||||||
|
this.applyHeaderStyles(worksheet);
|
||||||
|
this.configureWorksheet(worksheet);
|
||||||
|
this.saveExcelFile(workbook);
|
||||||
|
|
||||||
|
|
||||||
// Mapeamos los datos para tener solo las propiedades que queremos exportar
|
}
|
||||||
return data.map(item => {
|
/**
|
||||||
return {
|
* Añade los datos de la tabla al worksheet
|
||||||
'Empresa': item.empresa,
|
*/
|
||||||
'Código de cronograma': item.codigoCronograma,
|
private addDataToWorksheet(worksheet: any, table: Table): void {
|
||||||
'Etapa del Servicio': item.codigoCronogramaAjuste,
|
// Obtenemos los datos a exportar
|
||||||
'Nombre sistema': item.tipoCarga,
|
const data = table.filteredValue || table.value;
|
||||||
'Tipo de inversión': item.estadoRevision,
|
|
||||||
'Código de glosa PD': item.analista,
|
// Definimos las cabeceras
|
||||||
'Descripción glosa': item.fechaIngreso,
|
const headers = [
|
||||||
'Monto Inversión Total (UF)': '',
|
'Empresa', 'Código de cronograma', 'Etapa del Servicio',
|
||||||
'Año de Inicio': item.dato9,
|
'Nombre sistema', 'Tipo de inversión', 'Código de glosa PD',
|
||||||
'Año de Término': item.dato10,
|
'Descripción glosa', 'Año de Inicio', 'Año de Término',
|
||||||
'Mes de Término': item.dato11 || '',
|
'Estado aprobación'
|
||||||
'Nota': item.dato12 || '',
|
];
|
||||||
'Estado aprobación': item.dato13,
|
|
||||||
'Observación': ''
|
// Añadimos cabeceras y datos
|
||||||
|
worksheet.addRow(headers);
|
||||||
|
data.forEach(item => {
|
||||||
|
worksheet.addRow([
|
||||||
|
item.empresa,
|
||||||
|
item.codigoCronograma,
|
||||||
|
item.codigoCronogramaAjuste,
|
||||||
|
item.tipoCarga,
|
||||||
|
item.estadoRevision,
|
||||||
|
item.analista,
|
||||||
|
item.fechaIngreso,
|
||||||
|
item.dato9,
|
||||||
|
item.dato10,
|
||||||
|
item.dato13
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Aplica estilos a los encabezados de la tabla
|
||||||
|
*/
|
||||||
|
private applyHeaderStyles(worksheet: any): void {
|
||||||
|
const headerRow = worksheet.getRow(1);
|
||||||
|
headerRow.height = 25;
|
||||||
|
|
||||||
|
headerRow.eachCell((cell: any) => {
|
||||||
|
cell.font = { name: 'Arial', size: 12, bold: true, color: { argb: '000000' } };
|
||||||
|
cell.border = {
|
||||||
|
top: { style: 'thin' },
|
||||||
|
left: { style: 'thin' },
|
||||||
|
bottom: { style: 'thin' },
|
||||||
|
right: { style: 'thin' }
|
||||||
};
|
};
|
||||||
|
cell.alignment = { horizontal: 'center', vertical: 'middle' };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Aplica estilos al worksheet de Excel
|
* Configura aspectos generales de la hoja de trabajo
|
||||||
*/
|
*/
|
||||||
applyStyles(worksheet: XLSX.WorkSheet) {
|
private configureWorksheet(worksheet: any): void {
|
||||||
// Establecemos el estilo para los encabezados
|
// Ajustamos el ancho de las columnas automáticamente
|
||||||
const headerStyle = {
|
if (worksheet.columns) {
|
||||||
font: { bold: true, color: { rgb: 'FFFFFF' } },
|
worksheet.columns.forEach((column: any) => {
|
||||||
fill: { fgColor: { rgb: '0070C0' } },
|
if (column) {
|
||||||
alignment: { horizontal: 'center' }
|
let maxLength = 0;
|
||||||
};
|
column.eachCell({ includeEmpty: true }, (cell: any) => {
|
||||||
|
const columnLength = cell.value ? cell.value.toString().length : 10;
|
||||||
// Aplicar estilos a los encabezados (primera fila)
|
if (columnLength > maxLength) {
|
||||||
const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1');
|
maxLength = columnLength;
|
||||||
for (let col = range.s.c; col <= range.e.c; col++) {
|
}
|
||||||
const cellRef = XLSX.utils.encode_cell({ r: 0, c: col });
|
});
|
||||||
if (!worksheet[cellRef]) worksheet[cellRef] = { t: 's', v: '' };
|
column.width = maxLength < 10 ? 10 : maxLength + 2;
|
||||||
worksheet[cellRef].s = headerStyle;
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Congelamos la primera fila
|
||||||
|
worksheet.views = [{ state: 'frozen', xSplit: 0, ySplit: 1 }];
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Guarda el archivo Excel
|
||||||
|
*/
|
||||||
|
private async saveExcelFile(workbook: any): Promise<void> {
|
||||||
|
const today = new Date();
|
||||||
|
const fileName = `Cronograma_temporal_por_actualización_de_PD${today.getFullYear()}${(today.getMonth() + 1).toString().padStart(2, '0')}${today.getDate().toString().padStart(2, '0')}.xlsx`;
|
||||||
|
|
||||||
|
const buffer = await workbook.xlsx.writeBuffer();
|
||||||
|
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||||
|
FileSaver.saveAs(blob, fileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Guarda el buffer como un archivo Excel
|
|
||||||
*/
|
|
||||||
saveAsExcelFile(buffer: any, fileName: string): void {
|
|
||||||
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
|
|
||||||
const EXCEL_EXTENSION = '.xlsx';
|
|
||||||
const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
|
|
||||||
FileSaver.saveAs(data, fileName + '_' + new Date().getTime() + EXCEL_EXTENSION);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@ -123,7 +123,7 @@
|
|||||||
<button
|
<button
|
||||||
pButton
|
pButton
|
||||||
type="button"
|
type="button"
|
||||||
(click)="exportExcel(dt)"
|
(click)="exportExcelWithStyles(dt)"
|
||||||
icon="pi pi-file-excel"
|
icon="pi pi-file-excel"
|
||||||
class="p-button-success"
|
class="p-button-success"
|
||||||
label="Exportar a Excel"
|
label="Exportar a Excel"
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
import { Component } from '@angular/core';
|
import { Component } from '@angular/core';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { TableModule ,Table} from 'primeng/table';
|
import { TableModule, Table } from 'primeng/table';
|
||||||
import { InputTextModule } from 'primeng/inputtext';
|
import { InputTextModule } from 'primeng/inputtext';
|
||||||
import { SelectModule } from 'primeng/select';
|
import { SelectModule } from 'primeng/select';
|
||||||
import { TooltipModule } from 'primeng/tooltip';
|
import { TooltipModule } from 'primeng/tooltip';
|
||||||
import { ButtonModule } from 'primeng/button';
|
import { ButtonModule } from 'primeng/button';
|
||||||
import * as FileSaver from 'file-saver';
|
import * as FileSaver from 'file-saver';
|
||||||
import * as XLSX from 'xlsx';
|
import { Workbook } from 'exceljs';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-ajuste-pd',
|
selector: 'app-ajuste-pd',
|
||||||
@ -23,9 +23,9 @@ import * as XLSX from 'xlsx';
|
|||||||
})
|
})
|
||||||
export class AjustePdComponent {
|
export class AjustePdComponent {
|
||||||
selectedCity: any = '';
|
selectedCity: any = '';
|
||||||
empresas: any[] = [{name: 'Empresa A'}, {name: 'Empresa B'}, {name: 'Empresa C'}];
|
empresas: any[] = [{ name: 'Empresa A' }, { name: 'Empresa B' }, { name: 'Empresa C' }];
|
||||||
select1: any = '';
|
select1: any = '';
|
||||||
estadoAprobacion: any[] = [{name:'Rechazado'}, {name:'Aprobado'}];
|
estadoAprobacion: any[] = [{ name: 'Rechazado' }, { name: 'Aprobado' }];
|
||||||
products: any[] = [
|
products: any[] = [
|
||||||
{
|
{
|
||||||
empresa: 'Empresa A',
|
empresa: 'Empresa A',
|
||||||
@ -100,115 +100,152 @@ export class AjustePdComponent {
|
|||||||
dato14: 'green',
|
dato14: 'green',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exporta los datos de la tabla a un archivo Excel
|
* Exporta los datos de la tabla a Excel con estilos en los encabezados
|
||||||
* @param table Referencia a la tabla PrimeNG
|
* @param table Tabla PrimeNG a exportar
|
||||||
*/
|
*/
|
||||||
exportExcel(table: Table) {
|
exportExcelWithStyles(table: Table): void {
|
||||||
try {
|
// Creamos un nuevo libro de trabajo
|
||||||
// Obtenemos los datos a exportar (usamos los datos filtrados si existen)
|
const workbook = new Workbook();
|
||||||
const dataToExport = this.prepareDataForExport(table);
|
const worksheet = workbook.addWorksheet('Datos');
|
||||||
|
|
||||||
// Creamos el libro de Excel
|
// Obtenemos los datos y los cabeceros
|
||||||
const worksheet = XLSX.utils.json_to_sheet(dataToExport);
|
const data = table.filteredValue || table.value;
|
||||||
const workbook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
|
const headers = this.getHeaders();
|
||||||
|
|
||||||
// Aplicamos estilos a las celdas
|
// Añadimos los datos a la hoja
|
||||||
this.applyExcelStyles(worksheet);
|
this.populateWorksheet(worksheet, headers, data);
|
||||||
|
|
||||||
// Opciones de exportación
|
// Aplicamos estilos a los encabezados
|
||||||
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
|
this.styleHeaders(worksheet);
|
||||||
|
|
||||||
// Guardamos el archivo
|
// Configuramos propiedades generales de la hoja
|
||||||
this.saveAsExcelFile(excelBuffer, 'ajuste_pd');
|
this.configureWorksheet(worksheet, data.length);
|
||||||
|
|
||||||
console.log('Exportación a Excel completada con éxito');
|
// Exportamos el archivo
|
||||||
} catch (error) {
|
this.saveExcelFile(workbook);
|
||||||
console.error('Error al exportar a Excel:', error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prepara los datos para la exportación, traduciendo los nombres de columnas
|
* Devuelve los cabeceros para el archivo Excel
|
||||||
* @param table Referencia a la tabla PrimeNG
|
|
||||||
* @returns Array de objetos con los datos formateados para exportar
|
|
||||||
*/
|
*/
|
||||||
private prepareDataForExport(table: Table): any[] {
|
private getHeaders(): string[] {
|
||||||
// Si hay filtros aplicados, usamos los datos filtrados, de lo contrario todos los datos
|
return [
|
||||||
const data = table.filteredValue || table.value;
|
'Empresa',
|
||||||
|
'Código de cronograma',
|
||||||
// Mapeamos los datos para tener nombres de columnas en español y legibles
|
'Etapa del Servicio',
|
||||||
return data.map(item => {
|
'Nombre sistema',
|
||||||
return {
|
'Tipo de inversión',
|
||||||
'Empresa': item.empresa,
|
'Código de glosa PD',
|
||||||
'Código de cronograma': item.codigoCronograma,
|
'Descripción glosa',
|
||||||
'Etapa del Servicio': item.codigoCronogramaAjuste,
|
'Año de Inicio',
|
||||||
'Nombre sistema': item.tipoCarga,
|
'Año de Término',
|
||||||
'Tipo de inversión': item.estadoRevision,
|
'Estado aprobación'
|
||||||
'Código de glosa PD': item.analista,
|
];
|
||||||
'Descripción glosa': item.fechaIngreso,
|
}
|
||||||
'Año de Inicio': item.dato9,
|
|
||||||
'Año de Término': item.dato10,
|
/**
|
||||||
'Estado aprobación': item.dato13
|
* Rellena la hoja con los datos de la tabla
|
||||||
|
*/
|
||||||
|
private populateWorksheet(worksheet: any, headers: string[], data: any[]): void {
|
||||||
|
// Añadimos las cabeceras
|
||||||
|
worksheet.addRow(headers);
|
||||||
|
|
||||||
|
// Añadimos los datos
|
||||||
|
data.forEach(item => {
|
||||||
|
worksheet.addRow([
|
||||||
|
item.empresa,
|
||||||
|
item.codigoCronograma,
|
||||||
|
item.codigoCronogramaAjuste,
|
||||||
|
item.tipoCarga,
|
||||||
|
item.estadoRevision,
|
||||||
|
item.analista,
|
||||||
|
item.fechaIngreso,
|
||||||
|
item.dato9,
|
||||||
|
item.dato10,
|
||||||
|
item.dato13
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aplica estilos a los encabezados
|
||||||
|
*/
|
||||||
|
private styleHeaders(worksheet: any): void {
|
||||||
|
const headerRow = worksheet.getRow(1);
|
||||||
|
headerRow.height = 25;
|
||||||
|
|
||||||
|
headerRow.eachCell(cell => {
|
||||||
|
// Estilo de texto Encabezado
|
||||||
|
cell.font = {
|
||||||
|
name: 'Arial',
|
||||||
|
size: 12,
|
||||||
|
bold: true,
|
||||||
|
color: { argb: '000000' }
|
||||||
|
};
|
||||||
|
|
||||||
|
// Bordes
|
||||||
|
cell.border = {
|
||||||
|
top: { style: 'thin' },
|
||||||
|
left: { style: 'thin' },
|
||||||
|
bottom: { style: 'thin' },
|
||||||
|
right: { style: 'thin' }
|
||||||
|
};
|
||||||
|
|
||||||
|
// Alineación
|
||||||
|
cell.alignment = {
|
||||||
|
horizontal: 'center',
|
||||||
|
vertical: 'middle'
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Aplica estilos al worksheet de Excel para mejorar la presentación
|
* Configura propiedades generales de la hoja de trabajo
|
||||||
* @param worksheet Hoja de Excel a la que aplicar estilos
|
|
||||||
*/
|
*/
|
||||||
private applyExcelStyles(worksheet: XLSX.WorkSheet) {
|
private configureWorksheet(worksheet: any, dataLength: number): void {
|
||||||
// Definimos estilos para los encabezados
|
// Configuramos altura de fila predeterminada
|
||||||
const headerStyle = {
|
worksheet.properties.defaultRowHeight = 20;
|
||||||
font: { bold: true, color: { rgb: 'FFFFFF' } },
|
|
||||||
fill: { fgColor: { rgb: '007ACC' } }, // Color azul para los encabezados
|
|
||||||
alignment: { horizontal: 'center', vertical: 'center' }
|
|
||||||
};
|
|
||||||
|
|
||||||
// Aplicamos estilos a los encabezados (primera fila)
|
|
||||||
const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1');
|
|
||||||
for (let col = range.s.c; col <= range.e.c; col++) {
|
|
||||||
const cellRef = XLSX.utils.encode_cell({ r: 0, c: col });
|
|
||||||
if (!worksheet[cellRef]) worksheet[cellRef] = { t: 's', v: '' };
|
|
||||||
|
|
||||||
// Asignamos el estilo al encabezado
|
|
||||||
worksheet[cellRef].s = headerStyle;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ajustamos el ancho de las columnas automáticamente
|
// Ajustamos el ancho de las columnas automáticamente
|
||||||
const colWidths = [];
|
this.adjustColumnWidths(worksheet);
|
||||||
for (let col = range.s.c; col <= range.e.c; col++) {
|
|
||||||
colWidths.push({ wch: 15 }); // Ancho predeterminado
|
// Congelamos la primera fila
|
||||||
}
|
worksheet.views = [{ state: 'frozen', xSplit: 0, ySplit: 1 }];
|
||||||
worksheet['!cols'] = colWidths;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Guarda el buffer como un archivo Excel
|
* Ajusta el ancho de las columnas según el contenido
|
||||||
* @param buffer Datos del archivo Excel
|
|
||||||
* @param fileName Nombre base del archivo
|
|
||||||
*/
|
*/
|
||||||
private saveAsExcelFile(buffer: any, fileName: string): void {
|
private adjustColumnWidths(worksheet: any): void {
|
||||||
// Definimos el tipo MIME para archivos Excel
|
if (worksheet.columns) {
|
||||||
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
|
worksheet.columns.forEach(column => {
|
||||||
const EXCEL_EXTENSION = '.xlsx';
|
if (column) {
|
||||||
|
let maxLength = 0;
|
||||||
// Creamos un Blob con los datos
|
column.eachCell({ includeEmpty: true }, cell => {
|
||||||
const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
|
const columnLength = cell.value ? cell.value.toString().length : 10;
|
||||||
|
if (columnLength > maxLength) {
|
||||||
// Generamos un nombre de archivo con timestamp para evitar duplicados
|
maxLength = columnLength;
|
||||||
const today = new Date();
|
}
|
||||||
const formattedDate =
|
});
|
||||||
today.getFullYear().toString() +
|
column.width = maxLength < 10 ? 10 : maxLength + 2;
|
||||||
(today.getMonth() + 1).toString().padStart(2, '0') +
|
}
|
||||||
today.getDate().toString().padStart(2, '0') +
|
});
|
||||||
'_' +
|
}
|
||||||
today.getHours().toString().padStart(2, '0') +
|
|
||||||
today.getMinutes().toString().padStart(2, '0');
|
|
||||||
|
|
||||||
// Guardamos el archivo
|
|
||||||
FileSaver.saveAs(data, `${fileName}_${formattedDate}${EXCEL_EXTENSION}`);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/**
|
||||||
|
* Guarda el archivo Excel generado
|
||||||
|
*/
|
||||||
|
private saveExcelFile(workbook: any): void {
|
||||||
|
const today = new Date();
|
||||||
|
const fileName = `Cronograma_temporal_por_ajuste_de_PD${today.getFullYear()}${(today.getMonth() + 1).toString().padStart(2, '0')}${today.getDate().toString().padStart(2, '0')}.xlsx`;
|
||||||
|
|
||||||
|
workbook.xlsx.writeBuffer()
|
||||||
|
.then(buffer => {
|
||||||
|
const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||||
|
FileSaver.saveAs(blob, fileName);
|
||||||
|
})
|
||||||
|
.catch(error => console.error('Error al exportar a Excel:', error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -4,7 +4,7 @@
|
|||||||
"compileOnSave": false,
|
"compileOnSave": false,
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"outDir": "./dist/out-tsc",
|
"outDir": "./dist/out-tsc",
|
||||||
"strict": true,
|
"strict": false,
|
||||||
"noImplicitOverride": true,
|
"noImplicitOverride": true,
|
||||||
"noPropertyAccessFromIndexSignature": true,
|
"noPropertyAccessFromIndexSignature": true,
|
||||||
"noImplicitReturns": true,
|
"noImplicitReturns": true,
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user