我在使用 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 文件时显示的那样。有人有解决这个问题的办法吗?
Use 数组.map() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map, 字符串.replace() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace and Array.join() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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')
);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)