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