我在使用 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';
}
}
此屏幕截图显示了记录器输出。
我想将包含逗号的单元格中的字符串用双引号括起来,就像以文本格式保存和打开 CSV 文件时显示的那样。有没有人有办法解决这个问题?
使用 Array.map()、String.replace() 和 Array.join(),如下所示:
'use strict';
function test() {
const text = SpreadsheetApp.getActiveSheet().getDataRange().getDisplayValues();
const result = textArrayToCsv_(text);
console.log(result);
}
/**
* Converts text to a CSV format.
*
* Usage:
* const range = SpreadsheetApp.getActiveRange();
* const csvData = textArrayToCsv_(range.getDisplayValues());
*
* 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).
*
* @see https://en.wikipedia.org/wiki/Comma-separated_values#General_functionality
* @param {String[][]} data The text to convert to CSV.
* @param {String} escapeDoublequote Optional. Use '\\"' to prefix double quotes in data as in \" instead of the default "".
* @return {String} The text converted to CSV.
*/
function textArrayToCsv_(data, escapeDoublequote = '""') {
// version 1.1, written by --Hyde, 1 April 2024
// - see https://stackoverflow.com/a/72689533/13045193
return (
data.map(row => row.map(value => `"${String(value).replace(/"/g, escapeDoublequote)}"`))
.map(row => row.join(', '))
.join('\n')
);
}