【问题标题】:Prevent Auto-Format DriveApi 3 Google Apps script防止自动格式化 DriveApi 3 Google Apps 脚本
【发布时间】:2021-12-30 14:02:37
【问题描述】:

使用 Drive API3,我正在寻找一种方法来制作 Google 表格格式的 CSV 文件的副本,而无需将文本转换为数字,也无需将功能和日期转换为可以在 Google 中提出的表格菜单:

文件>导入>(选择您的 CSV 文件)> 取消勾选“将文本转换为数字、日期和公式”。

目前,我有一些类似的东西:

function convert(){
      var file = DriveApp.getFileById('1234');
      var resource = { title : "Title", mimeType : MimeType.GOOGLE_SHEETS,parents : [{id: file.getParents().next().getId()}],}

      Drive.Files.copy(resource,file.getId())
} 

为了说明我的示例:我的 CSV 文件“2021-25-03”中有一个文本,如果我运行宏,新电子表格会自动将我的文本格式化为日期,这不是我的目标。

TFR。

【问题讨论】:

  • 我必须为我糟糕的英语水平道歉。不幸的是,我无法理解你的问题。为了正确理解您的问题,能否提供示例输入输出情况作为图片?

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


【解决方案1】:

API 或 Apps 脚本中似乎没有设置来防止数字和日期的自动转换,但我们可以构建一个脚本来解决这个问题。有两个工具很有用:

  1. Apps 脚本的 Utilities.parseCsv() 方法,它将在 CSV 文件中构建一个包含值的二维数组(作为纯文本 - 它不解释数字和日期)。
  2. 事实上,Google 表格会将任何以单引号 ' 开头的值解释为文本。无论值是在 UI 中输入还是以编程方式输入,都是如此。

所以总体策略是:

  1. 照常复制文件(或者只是创建一个新的空白文件,因为我们会将值写入其中)。
  2. 解析 CSV 值并在每个值前添加 '
  3. 将这些修改后的值写入工作表。

类似这样的:

function convert(){
      var file = DriveApp.getFileById(CSV_FILE_ID);
      // Create the copy:
      var resource = { title : "Title", mimeType : MimeType.GOOGLE_SHEETS,parents : [{id: file.getParents().next().getId()}],}

      var sheetsFile = Drive.Files.copy(resource,file.getId())
      
      // Parse the original csv file:
      var csv = Utilities.parseCsv(file.getBlob().getDataAsString())
      // csv is a 2D array; prepend each value with a single quote:
      csv.forEach(function(row){
        row.forEach(function(value, i){
          row[i] = "'" + value
        })
      })
      // Open the first (and only) sheet in the file and overwrite the values with these modified ones:
      var sheet = SpreadsheetApp.openById(sheetsFile.id).getSheets()[0]
      sheet.getRange(1,1,csv.length, csv[0].length).setValues(csv)
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多