使用Google Apps Script从Drive导入HTML表格,如何校验最新数据?
问题描述
我是Google Apps Script新手,正在用它从Google云端硬盘的HTML文件中导入表格,但不知道如何校验导入的数据是否为最新版本。当前代码仅在工作表为空时导入数据,否则只会清空工作表,无法判断HTML文件是否有更新。原代码如下:
function myFunction2() { var fileId = "1UqMZe3FlUWgqslL2lH6AjrwgDDYYzH9s"; var spreadsheetId = "1ezNNoHNIalACU0gYiKSFrTkSXJNJewekRf0mP6yCWWc"; var sheetName = "Raw1"; var ss = SpreadsheetApp.openById(spreadsheetId); var sheet = ss.getSheetByName(sheetName); var sheetId = sheet.getSheetId(); var rowIndex = 0; if (sheet.getLastRow() == 0) { // Retrieve tables from HTML data. var html = DriveApp.getFileById(fileId).getBlob().getDataAsString(); var values = html.match(/<table[\w\s\S]+?<\/table>/gi); // Put the HTML tables to the Spreadsheet. values.forEach(function (e) { var resource = { requests: [{ pasteData: { html: true, data: e, coordinate: { sheetId: sheetId, rowIndex: rowIndex } } }] }; Sheets.Spreadsheets.batchUpdate(resource, spreadsheetId); rowIndex = sheet.getLastRow(); }) } else { sheet.clear(); } }
解决方案
要校验数据是否为最新版本,核心是对比HTML文件的最后修改时间,我们可以把这个时间记录在工作表的隐藏单元格或者单独的配置工作表中,每次运行脚本时先做时间比对:
修改后的代码
function importLatestHtmlTables() { const fileId = "1UqMZe3FlUWgqslL2lH6AjrwgDDYYzH9s"; const spreadsheetId = "1ezNNoHNIalACU0gYiKSFrTkSXJNJewekRf0mP6yCWWc"; const sheetName = "Raw1"; const ss = SpreadsheetApp.openById(spreadsheetId); const sheet = ss.getSheetByName(sheetName); const sheetId = sheet.getSheetId(); // 获取HTML文件的最后修改时间(转成时间戳方便对比) const htmlFile = DriveApp.getFileById(fileId); const latestFileTimestamp = htmlFile.getLastUpdated().getTime(); // 读取工作表中记录的上次更新时间(这里用A1单元格存储,可隐藏该列) const storedTimestampCell = sheet.getRange("A1"); const storedTimestamp = storedTimestampCell.getValue() || 0; // 对比时间戳,判断是否需要更新 if (latestFileTimestamp > storedTimestamp) { // 清空现有数据 sheet.clear(); // 导入HTML表格数据 const html = htmlFile.getBlob().getDataAsString(); const tables = html.match(/<table[\w\s\S]+?<\/table>/gi); let rowIndex = 0; tables.forEach(table => { const resource = { requests: [{ pasteData: { html: true, data: table, coordinate: { sheetId: sheetId, rowIndex: rowIndex } } }] }; Sheets.Spreadsheets.batchUpdate(resource, spreadsheetId); rowIndex = sheet.getLastRow(); }); // 更新记录的时间戳 storedTimestampCell.setValue(latestFileTimestamp); SpreadsheetApp.getUi().alert("数据已更新为最新版本"); } else { SpreadsheetApp.getUi().alert("当前数据已是最新版本,无需更新"); } }
关键步骤说明
- 记录文件修改时间:用
getFileById(fileId).getLastUpdated().getTime()获取HTML文件的最后修改时间戳,存储在工作表的A1单元格(可以右键隐藏A列避免误操作)。 - 时间比对逻辑:每次运行脚本时,先读取存储的时间戳,和当前文件的时间戳对比,只有当文件更新过(时间戳更大)时才执行导入操作。
- 优化原有逻辑:去掉了原代码中“为空才导入,否则清空”的不合理逻辑,改为仅在文件更新时清空并重新导入,避免不必要的清空操作。
额外建议
- 如果不想在数据工作表中存储时间戳,可以新建一个名为
Config的工作表,专门存放配置信息(比如文件ID、上次更新时间等),更便于管理。 - 可以设置脚本的定时触发器,让它自动定期检查并更新数据,无需手动运行。
内容的提问来源于stack exchange,提问作者Minh Chiến Hoàng
相关产品推荐
相关产品推荐

