Advertisement
viktormorales

Exportar datos de hoja de cálculo a una presentación de Google

Jun 21st, 2025
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 4.36 KB | Source Code | 0 0
  1. /**
  2.  * VER ARTÍCULO EN MI SITIO WEB
  3.  * https://viktormorales.com/diseno-y-desarrollo-web/exportar-datos-de-hoja-de-calculo-a-una-presentacion-de-google/
  4.  */
  5.  
  6. /**
  7.  * createVoucher()
  8.  * This function is used to create the voucher
  9.  */
  10. function createVoucher() {
  11.  
  12.   // Get data from Google Sheets
  13.   const sheet = SpreadsheetApp.getActiveSpreadsheet();
  14.   const sheetName = "DIA SPA";
  15.   const tab = sheet.getSheetByName(sheetName);
  16.  
  17.   // Access an slide presentation
  18.   const presentationId = "SLIDE_ID";
  19.   const presentation = SlidesApp.openById(presentationId);
  20.   const presentationName = presentation.getName();
  21.  
  22.   // Get the last non-empty row values
  23.   const lastRow = getLastRowInColumn(tab);
  24.   const getColumn = {
  25.     "issue_date": formatDateToSpanish(tab.getRange(lastRow,1).getValue()),
  26.     "due_date": formatDateToSpanish(tab.getRange(lastRow,2).getValue()),
  27.     "name": tab.getRange(lastRow,3).getValue()
  28.   }
  29.  
  30.   // If there is data on the sheet, continue with the process
  31.   if (lastRow > 1) {
  32.     // Mensaje
  33.     SpreadsheetApp.getActive().toast("Aguarde mientras se crea el archivo PDF");
  34.  
  35.     // Create a COPY of the original slide presentation
  36.     const copy = DriveApp.getFileById(presentationId).makeCopy(`Copy ${presentationName}`);
  37.     const copyId = copy.getId();
  38.     const presentationCopy = SlidesApp.openById(copyId);
  39.  
  40.     // Replace text holder in texts box
  41.     const slide = presentationCopy.getSlides()[0];
  42.     const elements = slide.getPageElements();
  43.     for (const element of elements) {
  44.       if (element.getPageElementType() === SlidesApp.PageElementType.SHAPE) {
  45.         var shape = element.asShape();
  46.         var textRange = shape.getText();
  47.         var originalText = textRange.asString().trim();
  48.  
  49.         if (originalText == "{{NAME}}") {
  50.           var newText = originalText.replace("{{NAME}}", getColumn["name"]);
  51.           textRange.setText(newText);
  52.         }
  53.  
  54.         if (originalText == "{{DUE_DATE}}") {
  55.           var newText = originalText.replace("{{DUE_DATE}}", getColumn["due_date"]);
  56.           textRange.setText(newText);
  57.         }
  58.       }
  59.     }
  60.  
  61.     // Save changes and close
  62.     presentationCopy.saveAndClose();
  63.  
  64.     // Export as PDF
  65.     exportAsPDF(copyId, tab, lastRow);
  66.   } else {
  67.     SpreadsheetApp.getActive().toast("No hay información para crear un voucher");
  68.   }
  69. }
  70.  
  71. /**
  72.  * exportPDF()
  73.  */
  74. function exportAsPDF(presentationId, tab, lastRow) {
  75.   // Folder ID to save VOUCHERS as PDF when exported
  76.   const folder = DriveApp.getFolderById("FOLDER_ID");
  77.  
  78.   // Export as PDF
  79.   const blob = DriveApp.getFileById(presentationId).getAs("application/pdf");
  80.   const FILENAME = {
  81.     "issue_date": formatDate(tab.getRange(lastRow,1).getValue()),
  82.     "due_date": formatDate(tab.getRange(lastRow,2).getValue()),
  83.     "name": tab.getRange(lastRow,3).getValue(),
  84.   }
  85.   const fileName = `${FILENAME["due_date"]} - ${FILENAME["name"]}.pdf`;
  86.   const pdfFile = folder.createFile(blob.setName(fileName));
  87.  
  88.   // Delete copy
  89.   DriveApp.getFileById(presentationId).setTrashed(true);
  90.  
  91.   SpreadsheetApp.getActive().toast("Se creó el PDF");
  92.  
  93. }
  94.  
  95. /**
  96.  * getLastRowInColumn()
  97.  * Get the last populated row from "tab"
  98.  */
  99. function getLastRowInColumn(tab) {
  100.   // Get the first column
  101.   const column = 1; // Column A = 1, B = 2, etc.
  102.  
  103.   // Get all values in the column
  104.   const values = tab.getRange(1, column, tab.getLastRow()).getValues();
  105.  
  106.   // Loop through all the rows
  107.   let lastRow = 0;
  108.   for (let i = values.length - 1; i >= 0; i--) {
  109.     if (values[i][0] !== "") {
  110.       lastRow = i + 1; // Adjust for 1-based index
  111.       break;
  112.     }
  113.   }
  114.  
  115.   return lastRow;
  116. }
  117.  
  118.  
  119. /**
  120.  * formatDate()
  121.  * Format dates to "yyyy-mm-dd" format
  122.  */
  123. function formatDate(date) {
  124.   if (!(date instanceof Date)) return date; // Return original if not a date
  125.   const year = date.getFullYear();
  126.   const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
  127.   const day = date.getDate(); // No leading zero for single-digit day
  128.  
  129.   return `${year}-${month}-${day}`;
  130. }
  131.  
  132. /**
  133.  * formatDateToSpanish()
  134.  * Format dates to "spanish" version
  135.  */
  136. function formatDateToSpanish(date) {
  137.   if (!(date instanceof Date)) return date;
  138.   const formatter = new Intl.DateTimeFormat('es-ES', {
  139.     year: 'numeric',
  140.     month: 'long',
  141.     day: 'numeric'
  142.   });
  143.  
  144.   return formatter.format(date); // e.g., "20 de junio de 2025"
  145. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement