Как сгенерировать и автоматически открыть Google Doc с данными с Google Sheet с помощью Appscript?Javascript

Форум по Javascript
Ответить Пред. темаСлед. тема
Anonymous
 Как сгенерировать и автоматически открыть Google Doc с данными с Google Sheet с помощью Appscript?

Сообщение Anonymous »

У меня есть этот существующий код, он создает документ Google, однако данные не заменяются и не открываются автоматически. Я надеялся, что документ Google тоже будет временным, но они продолжали накапливаться на моем диске каждый раз, когда я его тестировал. Есть ли какой-нибудь возможный способ сделать то, что я пытаюсь сделать?
code.gs

Код: Выделить всё

function printRouteSlip(formObject) {
const templateId = "url  of my google doc"; // Template Google Doc ID
const templateFile = DriveApp.getFileById(templateId);

// Make a copy of the template
const newDoc = templateFile.makeCopy(`Route Slip for ${formObject.trackingNumber}`);
const newDocId = newDoc.getId();
const doc = DocumentApp.openById(newDocId);
const body = doc.getBody();

// Replace placeholders in the document with actual data from formObject
body.replaceText("{{TimeStamp}}", formObject.timeStamp || "");
body.replaceText("{{TrackingNumber}}", formObject.trackingNumber || "");
body.replaceText("{{DateReceived}}", formObject.dateReceived || "");
body.replaceText("{{ReceivedBy}}", formObject.receivedBy || "");
body.replaceText("{{TransactionType}}", formObject.transactionType || "");
body.replaceText("{{Description}}", formObject.description || "");
body.replaceText("{{OriginOffice}}", formObject.originOffice || "");
body.replaceText("{{ActionTaken}}", formObject.actionTaken || "");
body.replaceText("{{Recipient}}", formObject.recipient || "");
body.replaceText("{{DateTransmitted}}", formObject.dateTransmitted || "");
body.replaceText("{{Remarks}}", formObject.remarks || "");
body.replaceText("{{EmailAddress}}", formObject.email_add || "");

// Save and close the document
doc.saveAndClose();

// Get the document URL
const docUrl = `https://docs.google.com/document/d/${newDocId}/edit`;

// Show the document in a modal for the user to print
const html = HtmlService.createHtmlOutput(`
Click the button below to open and print the document:
[url=${docUrl}]
Open Document
[/url]

window.onunload = function() {
google.script.run.deleteTempFile('${newDocId}');
};

`).setWidth(400).setHeight(200);
SpreadsheetApp.getUi().showModalDialog(html, "Print Route Slip");

Код: Выделить всё

function deleteTempFile(fileId) {
const file = DriveApp.getFileById(fileId);
if (file) {
file.setTrashed(true);
}
}
javascript.html

Код: Выделить всё

function preventFormSubmit(event) {
event.preventDefault(); // Prevent the form from submitting normally

Swal.fire({
title: "Are you sure?",
text: "You can no longer edit this once submitted.",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, submit it!"
}).then((result) => {
if (result.isConfirmed) {
addTimestamp();
Swal.fire({
title: 'Please Wait',
text: 'Transaction is being recorded.',
icon: "info",
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
}
});

google.script.run
.withSuccessHandler(function(trackingNumber) {
const formObject = {
timeStamp: document.getElementById('timeStamp').value,
trackingNumber: trackingNumber,
dateReceived: document.getElementById('dateReceived').value,
receivedBy: document.getElementById('receivedBy').value,
transactionType: document.getElementById('transactionType').value,
description: document.getElementById('description').value,
originOffice: document.getElementById('originOffice').value,
actionTaken: document.getElementById('actionTaken').value,
recipient: document.getElementById('recipient').value,
remarks: document.getElementById('remarks').value,
dateTransmitted: document.getElementById('dateTransmitted').value,
email_add: document.getElementById('email_add').value || ""  // Optional field
};

handleFormSubmit(formObject);

Swal.close();
Swal.fire({
title: 'Success!',
html: `The document tracking number is:
[b]${trackingNumber}[/b]`,
icon: 'success',
confirmButtonText: 'OK',
confirmButtonColor: '#3085d6'
}).then(() => {
Swal.fire({
title: "Do you want to print the data?",
icon: "question",
showCancelButton: true,
confirmButtonText: "Yes",
cancelButtonText: "No"
}).then((printResult) => {
if (printResult.isConfirmed) {
// Call the printRouteSlip function here
google.script.run.printRouteSlip(formObject);
}
});
});
})
.withFailureHandler(function(error) {
Swal.fire({
title: 'Error',
text: `An error occurred: ${error.message}`,
icon: 'error',
confirmButtonColor: '#d33'
});
})
.generateTrackingNumber();
}
});
}

Подробнее здесь: https://stackoverflow.com/questions/793 ... e-sheet-us
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Javascript»