使用 Apps 脚本将本地 xls 导入 Google Sheets

问题描述 投票:0回答:1

我想自动将我每周保存到笔记本电脑上指定本地文件夹的 xls 文件导入到 Google 表格中。

我想在每次导入完成时替换工作表中的数据。文件名每次都会改变,但总是以报告开头,所以我可以使用“报告*”

如果有人可以帮助编写脚本,我将不胜感激,这将节省我每次手动导入的时间

谢谢 马丁

我以前从未使用过 Google Apps 脚本扩展,并且在尝试将本地驱动器定义为文件名每次都会更改的位置时似乎遇到问题。

示例位置为 C:\Reports\,文件名始终以 Report (report123456.xls) 开头,例如,我想将其导入到名为“详细信息”的现有工作表中

excel google-apps-script google-sheets import-from-excel
1个回答
0
投票

您可以使用 Google 表格中的弹出提示上传本地 XLS 文件。 确保将脚本 importExcel 分配给按钮或菜单选项。

这是一个工作脚本:

function importExcel(e) {

  if (!e) {
    SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile("uploadExcelpopup"), "Upload PIMMS Excel file");
    return;
  }

  var file = Utilities.newBlob(...e);

  let config = {
    title: "[Temporary Google Sheet] " + file.getName(),
    mimeType: MimeType.GOOGLE_SHEETS
  };
  let tempSs = Drive.Files.insert(config, file);

  var 
  fileId = tempSs.id,
  source = SpreadsheetApp.openById(fileId),
  sourceSheet = source.getSheets()[0];

    SpreadsheetApp.getActive().toast('Extracting data','🔄 File uploaded',10);

  var
  sourceValues = sourceSheet.getRange(1,1,sourceSheet.getLastRow(),sourceSheet.getLastColumn()).getValues(),
  sheetDataset = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Dataset");

  sheetDataset.getRange(1, 1, sourceValues.length, sourceValues[0].length).setValues(sourceValues);

  DriveApp.getFileById(fileId).setTrashed(true);

    SpreadsheetApp.getActive().toast('', '✔️ Upload complete',10);
    
}

您还需要创建一个 HTML 文件:

<form>
  <input type="file" name="file" onchange="importExcel(this.parentNode)" accept=".xls,.xlsx,.xlsm" id="inputFile" >
  <font face = "Calibri" size = "3"> <br><div id="progress">⏳ Waiting</div></font>
</form>
<script>
function importExcel(e) {
  const div = document.getElementById("progress");
  div.innerHTML = "🔄 Uploading";
  const file = e.file.files[0];
  const f = new FileReader();
  f.onload = d => google.script.run.withSuccessHandler(_ => {
    div.innerHTML = "✔️ Done";
    setTimeout(google.script.host.close, 1000);
  }).importExcel([[...new Int8Array(d.target.result)], file.type, file.name]);
  f.readAsArrayBuffer(file);
  
}
</script>

这是基于#Tanaike CSV本地输入弹出建议:

Google 表格导入 CSV 弹出窗口

© www.soinside.com 2019 - 2024. All rights reserved.