Cấp độ lập trình: Cơ bản
Thời lượng: 15 phút
Loại dự án: Tự động hoá bằng trình đơn tuỳ chỉnh
Mục tiêu
- Hiểu rõ chức năng của giải pháp.
- Tìm hiểu chức năng của các dịch vụ Apps Script trong giải pháp này.
- Thiết lập tập lệnh.
- Chạy tập lệnh.
Thông tin về giải pháp này
Để tiết kiệm thời gian và giảm lỗi do phải sao chép và dán theo cách thủ công, bạn có thể
tự động nhập nội dung từ nhiều tài liệu vào một tài liệu chính.
Giải pháp này tập trung vào việc tổng hợp các báo cáo trạng thái dự án, nhưng bạn có thể chỉnh sửa báo cáo cho phù hợp với nhu cầu của mình.
Cách thức hoạt động
Tập lệnh sẽ tạo một thư mục để lưu trữ tài liệu mà bạn muốn nhập nội dung và tài liệu mẫu để bắt đầu nhập. Tập lệnh cũng bao gồm các hàm tạo tài liệu mẫu để minh hoạ giải pháp này.
Khi người dùng chọn Nhập bản tóm tắt từ trình đơn tuỳ chỉnh, tập lệnh sẽ lấy tất cả các tệp Tài liệu trong thư mục và lặp lại qua từng tệp. Tập lệnh sẽ tìm một chuỗi và loại tiêu đề cụ thể để xác định văn bản tóm tắt cần sao chép. Sau khi sao chép văn bản, tập lệnh sẽ thay đổi màu văn bản của chuỗi giá trị nhận dạng để giảm thiểu tình trạng trùng lặp. Tập lệnh sẽ dán các bản tóm tắt vào tài liệu chính, mỗi bản tóm tắt trong bảng một ô riêng.
Dịch vụ Apps Script
Giải pháp này sử dụng các dịch vụ sau:
- Dịch vụ tài liệu–Tạo mẫu và tài liệu nguồn mẫu. Lặp lại qua từng tài liệu nguồn để tìm bản tóm tắt dự án mới để nhập. Nhập các bản tóm tắt vào tài liệu chính.
Cập nhật tài liệu nguồn để tránh nhập bản tóm tắt nhiều lần.
- Dịch vụ Drive – Tạo một thư mục để lưu trữ tài liệu nguồn. Thêm tài liệu mẫu và tài liệu nguồn mẫu vào thư mục.
- Dịch vụ tiện ích – Định dạng ngày tập lệnh thêm vào tài liệu chính mỗi khi tập lệnh nhập các bản tóm tắt từ tài liệu nguồn.
- Dịch vụ cơ sở – Sử dụng lớp
Session
để lấy múi giờ của tập lệnh. Tập lệnh sử dụng múi giờ khi thêm ngày nhập vào tài liệu chính.
Điều kiện tiên quyết
Để sử dụng mẫu này, bạn cần có các điều kiện tiên quyết sau:
- Tài khoản Google (các tài khoản Google Workspace có thể
phải được quản trị viên phê duyệt).
- Một trình duyệt web có quyền truy cập vào Internet.
Thiết lập tập lệnh
Hãy nhấp vào nút bên dưới để tạo bản sao của tài liệu Nội dung tổng hợp.
Tạo bản sao
Chạy tập lệnh
Chạy bản minh hoạ bằng các tài liệu mẫu
- Nhấp vào Nhập bản tóm tắt > Định cấu hình
> Chạy thiết lập bản minh hoạ bằng tài liệu mẫu.
Bạn có thể cần phải làm mới trang để trình đơn tuỳ chỉnh này xuất hiện.
Khi được nhắc, hãy cho phép tập lệnh chạy.
Nếu màn hình xin phép bằng OAuth hiển thị cảnh báo, Ứng dụng này chưa được xác minh,
hãy tiếp tục bằng cách chọn Nâng cao >
Chuyển đến {Project Name} (không an toàn).
Nhấp lại vào Nhập bản tóm tắt > Định cấu hình
> Chạy thiết lập bản minh hoạ bằng tài liệu mẫu
một lần nữa.
Khi được nhắc, hãy sao chép URL của thư mục Drive để sử dụng trong một bước sau.
Nhấp vào OK.
Nhấp vào Nhập bản tóm tắt > Nhập bản tóm tắt.
Khi được nhắc, hãy nhấp vào OK.
Xem lại các bản tóm tắt dự án đã được nhập từ tài liệu mẫu.
Thêm và nhập bản tóm tắt
- Trong thẻ trình duyệt mới, hãy dán URL của thư mục đó để mở thư mục Project status (Trạng thái dự án).
- Mở tệp Project ABC (Dự án ABC).
- Tạo một bản tóm tắt mới để nhập bằng cách thêm nội dung sau vào cuối tài liệu:
- Nhập
Summary
và đặt kiểu văn bản thành Tiêu đề 3.
- Ngay bên dưới
Summary
, hãy chèn một bảng 1x1. Đảm bảo không có dòng trống nào ở giữa Summary
và bảng.
- Trong bảng, hãy nhập
Hello world!
.
- Chuyển về tài liệu chính rồi nhấp vào Nhập bản tóm tắt
> Nhập bản tóm tắt.
- Khi được nhắc, hãy nhấp vào OK.
- Xem dữ liệu nhập mới nhất ở cuối tài liệu.
Xem xét mã
Để xem lại mã Apps Script cho giải pháp này, hãy nhấp vào phần Xem mã nguồn bên dưới:
Xem mã nguồn
Setup.gs
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This file contains functions that create the template and sample documents.
*/
/**
* Runs full setup configuration, with option to include samples.
*
* Called from menu & setupWithSamples()
*
* @param {boolean} includeSamples - Optional, if true creates samples files. *
*/
function setupConfig(includeSamples) {
// Gets folder to store documents in.
const folder = getFolderByName_(PROJECT_FOLDER_NAME)
let msg =
`\nDrive Folder for Documents: '${PROJECT_FOLDER_NAME}'
\nURL: \n${folder.getUrl()}`
// Creates sample documents for testing.
// Remove sample document creation and add your own process as needed.
if (includeSamples) {
let filesCreated = 0;
for (let doc of samples.documents) {
filesCreated += createGoogleDoc(doc, folder, true);
}
msg += `\n\nFiles Created: ${filesCreated}`
}
const ui = DocumentApp.getUi();
ui.alert(`${APP_TITLE} [Setup]`, msg, ui.ButtonSet.OK);
}
/**
* Creates a single document instance in the application folder.
* Includes import settings already created [Heading | Keywords | Table]
*
* Called from menu.
*/
function createSampleFile() {
// Creates a new Google Docs document.
const templateName = `[Template] ${APP_TITLE}`;
const doc = DocumentApp.create(templateName);
const docId = doc.getId();
const msg = `\nDocument created: '${templateName}'
\nURL: \n${doc.getUrl()}`
// Adds template content to the body.
const body = doc.getBody();
body.setText(templateName);
body.getParagraphs()[0].setHeading(DocumentApp.ParagraphHeading.TITLE);
body.appendParagraph('Description').setHeading(DocumentApp.ParagraphHeading.HEADING1);
body.appendParagraph('');
const dateString = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'MMMM dd, yyyy');
body.appendParagraph(`${FIND_TEXT_KEYWORDS} - ${dateString}`).setHeading(APP_STYLE);
body.appendTable().appendTableRow().appendTableCell('TL;DR');
body.appendParagraph("");
// Gets folder to store documents in.
const folder = getFolderByName_(PROJECT_FOLDER_NAME)
// Moves document to application folder.
DriveApp.getFileById(docId).moveTo(folder);
const ui = DocumentApp.getUi();
ui.alert(`${APP_TITLE} [Template]`, msg, ui.ButtonSet.OK);
}
/**
* Configures application for demonstration by setting it up with sample documents.
*
* Called from menu | Calls setupConfig with option set to true.
*/
function setupWithSamples() {
setupConfig(true)
}
/**
* Sample document names and demo content.
* {object} samples[]
*/
const samples = {
'documents': [
{
'name': 'Project GHI',
'description': 'Google Workspace Add-on inventory review.',
'content': 'Reviewed all of the currently in-use and proposed Google Workspace Add-ons. Will perform an assessment on how we can reduce overlap, reduce licensing costs, and limit security exposures. \n\nNext week\'s goal is to report findings back to the Corp Ops team.'
},
{
'name': 'Project DEF',
'description': 'Improve IT networks within the main corporate building.',
'content': 'Primarily focused on 2nd thru 5th floors in the main corporate building evaluating the network infrastructure. Benchmarking tests were performed and results are being analyzed. \n\nWill submit all findings, analysis, and recommendations next week for committee review.'
},
{
'name': 'Project ABC',
'description': 'Assess existing Google Chromebook inventory and recommend upgrades where necessary.',
'content': 'Concluded a pilot program with the Customer Service department to perform inventory and update inventory records with Chromebook hardware, Chrome OS versions, and installed apps. \n\nScheduling a work plan and seeking necessary go-forward approvals for next week.'
},
],
'common': 'This sample document is configured to work with the Import summaries custom menu. For the import to work, the source documents used must contain a specific keyword (currently set to "Summary"). The keyword must reside in a paragraph with a set style (currently set to "Heading 3") that is directly followed by a single-cell table. The table contains the contents to be imported into the primary document.\n\nWhile those rules might seem precise, it\'s how the application programmatically determines what content is meant to be imported and what can be ignored. Once a summary has been imported, the script updates the heading font to a new color (currently set to Green, hex \'#2e7d32\') to ensure the app ignores it in future imports. You can change these settings in the Apps Script code.'
}
/**
* Creates a sample document in application folder.
* Includes import settings already created [Heading | Keywords | Table].
* Inserts demo data from samples[].
*
* Called from menu.
*/
function createGoogleDoc(document, folder, duplicate) {
// Checks for duplicates.
if (!duplicate) {
// Doesn't create file of same name if one already exists.
if (folder.getFilesByName(document.name).hasNext()) {
return 0 // File not created.
}
}
// Creates a new Google Docs document.
const doc = DocumentApp.create(document.name).setName(document.name);
const docId = doc.getId();
// Adds boilerplate content to the body.
const body = doc.getBody();
body.setText(document.name);
body.getParagraphs()[0].setHeading(DocumentApp.ParagraphHeading.TITLE);
body.appendParagraph("Description").setHeading(DocumentApp.ParagraphHeading.HEADING1);
body.appendParagraph(document.description);
body.appendParagraph("Usage Instructions").setHeading(DocumentApp.ParagraphHeading.HEADING1);
body.appendParagraph(samples.common);
const dateString = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'MMMM dd, yyyy');
body.appendParagraph(`${FIND_TEXT_KEYWORDS} - ${dateString}`).setHeading(APP_STYLE);
body.appendTable().appendTableRow().appendTableCell(document.content);
body.appendParagraph("");
// Moves document to application folder.
DriveApp.getFileById(docId).moveTo(folder);
// Returns if successfully created.
return 1
}
Người đóng góp
Mẫu này được Google duy trì với sự trợ giúp của các chuyên gia nhà phát triển của Google.
Các bước tiếp theo