una tutorial script pegar lenguaje insertar imagenes imagen hoja google español ejemplos como celda calculo apps google-apps-script google-docs google-docs-api

google-apps-script - tutorial - manual de google apps script



Suba una imagen a una hoja de cálculo de Google (5)

Estoy haciendo un concurso de fotografía, el competidor debe registrarse usando un formulario de registro de Google y subir también su foto. Busqué en Internet para encontrar un script de Google que se puede insertar en un formulario para cargar un archivo con los formularios de Google, pero no pude encontrar nada. ¿Es posible y cómo, e incluso si puede haber otras ideas para hacerlo, por favor hágamelo saber.


Prueba esto

function insertImage() { // Retrieve an image from the web. var resp = UrlFetchApp.fetch("http://www.google.com/intl/en_com/images/srpr/logo2w.png"); // Create a document. var doc = DocumentApp.openById(""); // Append the image to the first paragraph. doc.getChild(0).asParagraph().appendInlineImage(resp); }

Este enlace también podría ayudarte :)

http://code.google.com/googleapps/appsscript/class_documentapp_listitem.html#appendInlineImage

Feliz codificación!


Aquí hay una posible sugerencia de flujo de trabajo que incluye un formulario, una hoja de cálculo con respuestas y un documento con imágenes incluidas.

la forma es verificable aquí

la hoja de cálculo se puede ver aquí

el documento se puede ver aquí

Ver EDIT 2

NOTAS:

  1. por ahora solo funciona con imágenes pequeñas, tengo que encontrar una solución para eso. (ver EDITAR)
  2. la inserción de la imagen en la hoja de cálculo no funciona, he comentado esta línea por ahora ...

Y aquí está el código completo, todavía un borrador, pero creo que podría implementarse completamente si encontramos una solución a los problemas antes mencionados.

EDITAR: El tamaño de la imagen no es relevante, tuve éxito con imágenes 4 veces más grandes que el tamaño de página pero en formato PNG. Parece que .png es mucho más confiable en este contexto, ¡eso es después de todas buenas noticias! Por cierto, puedo usar indiferentemente el blob, el archivo de imagen o la llamada miniatura (que tiene el mismo tamaño que el original ;-) y siempre obtengo el mismo resultado. Supongo que tendré que publicar una pregunta sobre eso en otra publicación: -D =

var submissionSSKey = ''0AnqSFd3iikE3dGFsUWNpb08zVWx5YjFRckloZ0NFZGc''; var docurl = ''https://docs.google.com/document/d/1E6yoROb52QjICsEbGVXIBdz8KhdFU_5gimWlJUbu8DI/'' var listitems = [''Select a category'',''Portrait'',''Landscape'',''Nude'',''Night shots'',''Nature'',''Various''] var Panelstyle = {''background'':''#dddddd'',''padding'':''40px'',''borderStyle'':''ridge'',''borderWidth'':''15PX'',''borderColor'':''#aaaaaa''} function doGet() { var app = UiApp.createApplication().setTitle(''Photography contest'').setStyleAttribute(''padding'',''50PX''); var panel = app.createFormPanel().setStyleAttributes(Panelstyle).setPixelSize(400, 200); var title = app.createHTML(''<B>Photography contest</B>'').setStyleAttribute(''color'',''grey'').setStyleAttribute(''fontSize'',''25PX''); var grid = app.createGrid(6,2).setId(''grid''); var list1 = app.createListBox().setName(''list1''); for(var i in listitems){list1.addItem(listitems[i])} var Textbox1 = app.createTextBox().setWidth(''150px'').setName(''TB1''); var email = app.createTextBox().setWidth(''150px'').setName(''mail''); var upLoad = app.createFileUpload().setName(''uploadedFile''); var submitButton = app.createSubmitButton(''<B>Submit</B>''); var warning = app.createHTML(''Please fill in all fields'').setStyleAttribute(''background'',''#bbbbbb'').setStyleAttribute(''fontSize'',''20px''); //file upload var cliHandler2 = app.createClientHandler() .validateLength(Textbox1, 1, 40).validateNotMatches(list1,''Select a category'').validateEmail(email).validateNotMatches(upLoad, ''FileUpload'') .forTargets(submitButton).setEnabled(true) .forTargets(warning).setHTML(''Now you can submit your form'').setStyleAttribute(''background'',''#99FF99'').setStyleAttribute(''fontSize'',''12px''); //Grid layout of items on form grid.setWidget(0, 1, title) .setText(1, 0, ''Category'') .setWidget(1, 1, list1.addClickHandler(cliHandler2)) .setText(2, 0, ''Name'') .setWidget(2, 1, Textbox1.addClickHandler(cliHandler2)) .setText(3, 0, ''Email'') .setWidget(3, 1, email) .setText(4, 0, ''File Upload'') .setWidget(4, 1, upLoad.addChangeHandler(cliHandler2)) .setWidget(5, 0, submitButton) .setWidget(5, 1, warning); var cliHandler = app.createClientHandler().forTargets(warning).setHTML(''<B>PLEASE WAIT WHILE THE FILE IS UPLOADING<B>'').setStyleAttribute(''background'',''yellow''); submitButton.addClickHandler(cliHandler).setEnabled(false); panel.add(grid); app.add(panel); return app; } function doPost(e) { var app = UiApp.getActiveApplication(); var ListVal = e.parameter.list1; var textVal = e.parameter.TB1; var Email = e.parameter.mail; var fileBlob = e.parameter.uploadedFile; var img = DocsList.createFile(fileBlob); try{ var folder = DocsList.getFolder(''photos''); }catch(e){DocsList.createFolder(''photos'');var folder = DocsList.getFolder(''photos'')} img.addToFolder(folder); img.removeFromFolder(DocsList.getRootFolder()) var sheet = SpreadsheetApp.openById(submissionSSKey).getSheetByName(''Sheet1''); var lastRow = sheet.getLastRow(); // var image = sheet.insertImage(img.getUrl(), 4, lastRow+1) var targetRange = sheet.getRange(lastRow+1, 1, 1, 4).setValues([[ListVal,textVal,Email,img.getUrl()]]); var GDoc = DocumentApp.openByUrl(docurl) GDoc.appendTable([[''Category : ''+ListVal,''Name : ''+textVal,''Email : ''+Email]]) var par = GDoc.appendParagraph(''IMAGE PREVIEW'') par.insertInlineImage(1, img.getThumbnail()) GDoc.appendHorizontalRule(); GDoc.saveAndClose(); app.add(app.createLabel(''Thank you for submitting'')); return app }

EDIT 2: He encontrado soluciones para (casi) todos los problemas ... Aquí está el nuevo código (solo la parte doPost) que proporciona escala de imagen automática para la vista previa del documento. Jpg, png o cualquier otro formato de imagen habitual compatible ... y muestra el tamaño inicial + peso. Actualicé el formulario de prueba en línea.

El problema de la hoja de cálculo no tiene solución por ahora, vea el número 145 , así que utilizo solo un enlace al archivo de imagen, pero este no tiene vista previa como se indica en el número 1239, pero el documento, como funciona ahora, es una solución agradable y útil (en mi opinión :-).

function doPost(e) { var app = UiApp.getActiveApplication(); var ListVal = e.parameter.list1; var textVal = e.parameter.TB1; var Email = e.parameter.mail; var fileBlob = e.parameter.uploadedFile; var blob = fileBlob.setContentTypeFromExtension() var img = DocsList.createFile(blob); try{ var folder = DocsList.getFolder(''photos''); }catch(e){DocsList.createFolder(''photos'');var folder = DocsList.getFolder(''photos'')} img.addToFolder(folder); img.removeFromFolder(DocsList.getRootFolder()); var weight = parseInt(img.getSize()/1000); var sheet = SpreadsheetApp.openById(submissionSSKey).getSheetByName(''Sheet1''); var lastRow = sheet.getLastRow(); var targetRange = sheet.getRange(lastRow+1, 1, 1, 4).setValues([[ListVal,textVal,Email,img.getUrl()]]); var GDoc = DocumentApp.openByUrl(docurl) GDoc.appendTable([[''Category : ''+ListVal,''Name : ''+textVal,''Email : ''+Email]]) var inlineI = GDoc.appendImage(img); var width = inlineI.getWidth(); var newW = width; var height = inlineI.getHeight(); var newH = height; var ratio = width/height Logger.log(''w=''+width+''h=''+height+'' ratio=''+ratio); if(width>640){ newW = 640; newH = parseInt(newW/ratio); } inlineI.setWidth(newW).setHeight(newH) GDoc.appendParagraph(''IMAGE size : ''+width+'' x ''+height+'' (eventually) resized to ''+newW+'' x ''+newH+'' for PREVIEW (''+weight+'' kB) ''); GDoc.appendHorizontalRule(); GDoc.saveAndClose(); app.add(app.createLabel(''Thank you for submitting'')); return app }


Gracias a la reciente publicación de jfreake, terminé resolviendo todos los problemas, incluido el de mostrar las imágenes en la propia hoja de cálculo. Aquí está el código final que publico en una respuesta separada para mayor comodidad y legibilidad.

var submissionSSKey = ''0AnqSFd3iikE3dGFsUWNpb08zVWx5YjFRckloZ0NFZGc''; var docurl = ''https://docs.google.com/document/d/1E6yoROb52QjICsEbGVXIBdz8KhdFU_5gimWlJUbu8DI/'' var listitems = [''Select a category'',''Portrait'',''Landscape'',''Nude'',''Night shots'',''Nature'',''Various''] var Panelstyle = {''background'':''#dddddd'',''padding'':''40px'',''borderStyle'':''solid'',''borderWidth'':''10PX'',''borderColor'':''#bbbbbb''} function doGet() { var app = UiApp.createApplication().setTitle(''Photography contest'').setStyleAttribute(''padding'',''50PX''); var panel = app.createFormPanel().setStyleAttributes(Panelstyle).setPixelSize(400, 200); var title = app.createHTML(''<B>Photography contest</B>'').setStyleAttribute(''color'',''grey'').setStyleAttribute(''fontSize'',''25PX''); var grid = app.createGrid(6,2).setId(''grid''); var list1 = app.createListBox().setName(''list1'').setWidth(''130''); for(var i in listitems){list1.addItem(listitems[i])} var Textbox1 = app.createTextBox().setWidth(''150px'').setName(''TB1''); var email = app.createTextBox().setWidth(''150px'').setName(''mail''); var upLoad = app.createFileUpload().setName(''uploadedFile''); var submitButton = app.createSubmitButton(''<B>Submit</B>''); var warning = app.createHTML(''Please fill in all fields'').setStyleAttribute(''background'',''#bbbbbb'').setStyleAttribute(''fontSize'',''18px''); //file upload var cliHandler2 = app.createClientHandler() .validateLength(Textbox1, 1, 40).validateNotMatches(list1,''Select a category'').validateEmail(email).validateNotMatches(upLoad, ''FileUpload'') .forTargets(submitButton).setEnabled(true) .forTargets(warning).setHTML(''Now you can submit your form'').setStyleAttribute(''background'',''#99FF99'').setStyleAttribute(''fontSize'',''12px''); //Grid layout of items on form grid.setWidget(0, 1, title) .setText(1, 0, ''Category'') .setWidget(1, 1, list1.addClickHandler(cliHandler2)) .setText(2, 0, ''Name'') .setWidget(2, 1, Textbox1.addClickHandler(cliHandler2)) .setText(3, 0, ''Email'') .setWidget(3, 1, email) .setText(4, 0, ''Image File'') .setWidget(4, 1, upLoad.addChangeHandler(cliHandler2)) .setWidget(5, 0, submitButton) .setWidget(5, 1, warning); var cliHandler = app.createClientHandler().forTargets(warning).setHTML(''<B>PLEASE WAIT WHILE THE FILE IS UPLOADING<B>'').setStyleAttribute(''background'',''yellow''); submitButton.addClickHandler(cliHandler).setEnabled(false); panel.add(grid); app.add(panel); return app; } function doPost(e) { var app = UiApp.getActiveApplication(); var ListVal = e.parameter.list1; var textVal = e.parameter.TB1; var Email = e.parameter.mail; var fileBlob = e.parameter.uploadedFile; var blob = fileBlob.setContentTypeFromExtension() var img = DocsList.createFile(blob); try{ var folder = DocsList.getFolder(''photos''); }catch(e){DocsList.createFolder(''photos'');var folder = DocsList.getFolder(''photos'')} img.addToFolder(folder); img.removeFromFolder(DocsList.getRootFolder()); var weight = parseInt(img.getSize()/1000); var sheet = SpreadsheetApp.openById(submissionSSKey).getSheetByName(''Sheet1''); var lastRow = sheet.getLastRow(); var targetRange = sheet.getRange(lastRow+1, 1, 1, 4).setValues([[ListVal,textVal,Email,"https://drive.google.com/uc?export=view&id="+img.getId()]]); var imageInsert = sheet.getRange(lastRow+1, 5).setFormula(''=image("https://drive.google.com/uc?export=view&id=''+img.getId()+''")''); sheet.setRowHeight(lastRow+1, 80); var GDoc = DocumentApp.openByUrl(docurl) GDoc.appendTable([[''Category : ''+ListVal,''Name : ''+textVal,''Email : ''+Email]]) var inlineI = GDoc.appendImage(img); var width = inlineI.getWidth(); var newW = width; var height = inlineI.getHeight(); var newH = height; var ratio = width/height; Logger.log(''w=''+width+''h=''+height+'' ratio=''+ratio); if(width>640){ newW = 640; newH = parseInt(newW/ratio); } inlineI.setWidth(newW).setHeight(newH) GDoc.appendParagraph(''IMAGE size : ''+width+'' x ''+height+'' (eventually) resized to ''+newW+'' x ''+newH+'' for PREVIEW (''+weight+'' kB) ''); GDoc.appendHorizontalRule(); GDoc.saveAndClose(); app.add(app.createLabel(''Thank you for submitting'')); return app }

los enlaces son los mismos: aplicación SS doc


Para obtener un enlace directo a la imagen en la hoja de cálculo, use la función getID lugar de getUrl y getUrl la URL a Gdrive .

Cambia esto:

var targetRange = sheet.getRange(lastRow+1, 1, 1, 4) .setValues([[ListVal,textVal,Email,img.getUrl()]]);

A esto:

var targetRange = sheet.getRange(lastRow+1, 1, 1, 4) .setValues([[ListVal,textVal,Email,"https://drive.google.com/uc?export=view&id="+img.getId()]]);


EDITAR : Actualizo el código un poco, porque como yyk mencionó, UiApp "doclist" obsoleta desde el 11 de diciembre de 2014. Lo uso para crear un trombinoscopio (no conozco la palabra en inglés, quizás la galería de grupos) en un documento de Google, las personas subieron su nombre de imagen nd en un formulario. No uso una hoja de cálculo. Aquí está el código:

function doGet(e) { var app = UiApp.createApplication().setTitle(''Trombi''); var panel = app.createFormPanel(); var grid = app.createGrid(3,2).setId(''registrationGrid''); var nameLabel = app.createLabel(''Name''); var nameTextbox = app.createTextBox().setWidth(''150px'').setName(''Name''); var submitButton = app.createSubmitButton(''<B>send</B>''); var warning = app.createHTML(''<B>Please wait<B>'').setStyleAttribute(''background'',''yellow'').setVisible(false) //file upload var upLoadTypeLabel = app.createLabel(''File to Upload''); var upLoad = (app.createFileUpload().setName(''thefile'')); //Grid layout of items on form grid.setWidget(0, 0, nameLabel) .setWidget(0, 1, nameTextbox) .setWidget(1, 0, upLoadTypeLabel) .setWidget(1, 1, upLoad) .setWidget(2, 0, submitButton) .setWidget(2, 1, warning) var cliHandler = app.createClientHandler().forTargets(warning).setVisible(true) submitButton.addClickHandler(cliHandler); panel.add(grid); app.add(panel); return app;} function doPost(e) { var app = UiApp.getActiveApplication(); var Name = e.parameter.Name; //app.getElementById(''info'').setVisible(true).setStyleAttribute(''color'',''red''); // data returned is a blob for FileUpload widget var fileBlob = e.parameter.thefile; var doc = DriveApp.createFile(fileBlob).setName(Name); var doc = DocumentApp.openById(''your key''); var body = doc.getBody(); var inlineI = body.appendImage(fileBlob); var width = inlineI.getWidth(); var newW = width; var height = inlineI.getHeight(); var newH = height; var ratio = width/height; Logger.log(''w=''+width+''h=''+height+'' ratio=''+ratio); if(width>200){ newW = 200; newH = parseInt(newW/ratio); } inlineI.setWidth(newW).setHeight(newH) body.appendParagraph(Name); body.appendHorizontalRule(); doc.saveAndClose(); app.add(app.createLabel(''success'')); return app }