【问题标题】:Convert text file into SpreadSheet Google Apps Script将文本文件转换为电子表格 Google Apps 脚本
【发布时间】:2021-09-18 00:13:12
【问题描述】:

我正在寻找一种方法,将原始文件转换为 .txt,然后使用 Google Apps 脚本转换为电子表格。

我已经看到了一种使用此脚本(使用 Drive API V2)将 xls 转换为 Google 电子表格的方法:

function convert_XLS_To_SpreadSheet(){
  var folder = DriveApp.getFoldersByName('RootFolder').next().getFoldersByName('depository').next();
  var txtFile = folder.getFilesByName('file.xls').next();
  Logger.log('Text File : ' + txtFile);

  
  var resource = {
    title : txtFile.getName(),
    mimeType : MimeType.GOOGLE_SHEETS,
    parents: [{id : folder.getId()}],
  }

  Drive.Files.insert(resource, txtFile.getBlob(),{
    convert: true
  });

  txtFile.setTrashed(true);
}

我尝试通过将我想要的文件替换为 txt 格式来做同样的事情,但即使我提供了正确的 MimeType,它也会给我一个 Google Doc。

【问题讨论】:

  • 澄清一下:什么是“粗鲁”文件?
  • 分隔符是什么?
  • 嗨,分隔符是 TAB @Cooper
  • Brut File -> 一个没有扩展名的文件@andrewjames
  • 什么是行尾分隔符?

标签: google-apps-script google-sheets google-drive-api


【解决方案1】:

列分隔符:\t

行分隔符:\n

代码:

function bf2ss() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const file = DriveApp.getFileById('fileId');
  let lA = file.getBlob().getDataAsString().split(/\n/);
  let fA = lA.map(r => r.split(/\t/));
  sh.clearContents();
  sh.getRange(1,1,fA.length,fA[0].length).setValues(fA);
}

表 1:

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9

【讨论】:

  • 非常感谢,效果很好;我不明白“行尾分隔符”以为它是一个特定的字符,但现在没关系!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多