簡體   English   中英

如何使用 Google Apps 腳本將 Google 表格單元格中的文本字符串解析為 CSV 文件?

[英]How do I parse text strings in Google Sheets cells to a CSV file with Google Apps Script?

我無法使用 Google Apps 腳本解析 Google 表格單元格中的字符串。 我使用了 JavaScript 方法Array.indexOf ,但未能找到單元格中字符串中存在的字符。 我試圖在單元格中字符串的字母之間插入下划線,但在每個單元格的字符串開頭只插入了一個下划線。

這是我的代碼:

function testCSV() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = ss.getSheets()[0];
  const range = sheet.getDataRange();
  const values = range.getValues();
  let csvStr = "";
  Logger.log(values);
  for (let i = 0; i < values.length; i++) {
    let row = "";
    for (let j = 0; j < values[i].length; j++) {
      if (values[i][j]) {
        row = row + "_" + values[i][j];
      }
      row = row + ",";
    }
    row = row.substring(0, (row.length-1));
    Logger.log(row);
    csvStr += row + '\n';
  }
}

此屏幕截圖顯示了 Logger 輸出。

記錄器輸出

我想用雙引號將字符串括在其中包含逗號的單元格中,就像以文本格式保存和打開 CSV 文件時顯示的那樣。 有沒有人有這個問題的解決方案?

我的電子表格

使用Array.map()String.replace()Array.join() ,如下所示:

function test() {
  const text = SpreadsheetApp.getActiveSheet().getDataRange().getDisplayValues();
  const result = textArrayToCsv_(text);
  console.log(result);
}


/**
* Converts text to a CSV format.
* When the data looks like this:

  header A1       header B1                   header C1
  text A2         text with comma, in B2      text with "quotes" in C2

* ...the function will return this:

  "header A1", "header B1", "header C1"
  "text A2", "text with comma, in B2", "text with \"quotes\" in C2"

* Lines end in a newline character (ASCII 10).
*
* @param {String[][]} data The text to convert to CSV.
* @return {String} The text converted to CSV.
*/
function textArrayToCsv_(data) {
  // version 1.0, written by --Hyde, 20 June 2022
  //  - see https://stackoverflow.com/a/72689533/13045193
  'use strict';
  return (
    data.map(row => row.map(value => `"${value.replace(/"/g, '\\"')}"`))
      .map(row => row.join(', '))
      .join('\n')
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM