我無法使用 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 檔案時顯示的一樣。有沒有人有這個問題的解決方案?

uj5u.com熱心網友回復:
使用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')
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/494445.html
上一篇:使用回圈在多個復選框上運行腳本
