You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GAS使用Utilities.parseCsv()导入CSV时货币格式转换问题

问题诊断
  • 替换逻辑错误:你当前的替换顺序是先将逗号替换为点,再将点替换为逗号,最终效果等于千分位逗号、小数点都被替换为逗号,完全没有达到转换目标;且原生replace()方法不传全局正则的情况下,只会替换第一个匹配到的字符,无法处理全量内容。
  • 操作对象错误:直接对原始CSV字符串做全局替换,会把作为字段分隔符的逗号也替换为点,导致后续Utilities.parseCsv()无法正确拆分字段,最终出现数值混乱、结构错位的问题。
修正方案

正确处理逻辑为先解析CSV得到结构化二维数组,再对每个单元格内容单独做格式转换,完全不会触碰CSV分隔符,避免结构被破坏。
修正后的完整代码如下:

//Imports a CSV file in Google Drive into the Google Sheet
function importCSVFromDrive() {
  var fileName = promptUserForInput("Please enter the name of the CSV file to import from Google Drive:");
  var files = findFilesInDrive(fileName);
  if(files.length === 0) {
    displayToastAlert("No files with name \"" + fileName + "\" were found in Google Drive.");
    return;
  } else if(files.length > 1) {
    displayToastAlert("Multiple files with name " + fileName +" were found. This program does not support picking the right file yet.");
    return;
  }
  var file = files[0];
  var csvString = file.getBlob().getDataAsString();
  // 先解析CSV得到结构化数据,避免破坏分隔符
  var contents = Utilities.parseCsv(csvString);
  // 遍历所有单元格转换货币格式
  var convertedContents = contents.map(row => {
    return row.map(cell => {
      if (typeof cell === 'string') {
        return convertUsCurrencyToEu(cell);
      }
      return cell;
    });
  });
  var sheetName = writeDataToSheet(convertedContents);
  displayToastAlert("The CSV file was successfully imported into " + sheetName + ".");
}

// 转换美式货币格式为欧洲格式
function convertUsCurrencyToEu(text) {
  // 匹配1,000.57、2,345,678.99这类标准美式货币数值
  const usCurrencyRegex = /(\d{1,3}(?:,\d{3})*)\.(\d{2})/g;
  return text.replace(usCurrencyRegex, (match, integerPart, decimalPart) => {
    // 整数部分千分位逗号替换为点,再用逗号拼接小数部分
    return integerPart.replace(/,/g, '.') + ',' + decimalPart;
  });
}

//Prompts the user for input and returns their response
function promptUserForInput(promptText) {
  var ui = SpreadsheetApp.getUi();
  var prompt = ui.prompt(promptText);
  var response = prompt.getResponseText();
  return response;
}

//Returns files in Google Drive that have a certain name.
function findFilesInDrive(filename) {
  var files = DriveApp.getFilesByName(filename);
  var result = [];
  while(files.hasNext())
    result.push(files.next());
  return result;
}

//Inserts a new sheet and writes a 2D array of data in it
function writeDataToSheet(data) {
  var ss = SpreadsheetApp.getActive();
  sheet = ss.insertSheet();
  sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
  return sheet.getName();
}

内容的提问来源于stack exchange,提问作者Bierbaron1920

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 06:12:02