You need to enable JavaScript to run this app. 如何通过Google Apps Script确保导入Google Sheets的数值为数字类型
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Apps Script确保导入Google Sheets的数值为数字类型

解决Google Sheets Apps Script导入CSV数值为文本类型的问题

我是Google Sheets的Apps Script新手,现有函数可获取并解析指定CSV文件,但导入Google Sheets后的数值数据并非数字类型,导致表格数学函数无法正常使用。目前通过=arrayformula(cell+0)作为临时解决办法,希望能直接将数据以数字类型导入。

原代码如下:

function ImportPlayerMPLog(playerID) {
 // Get the Link to the CSV file for player with Player ID Number
 let link = 'https://www.moneypuck.com/moneypuck/playerData/careers/gameByGame/regular/skaters/'
 link += playerID
 link += '.csv'
  // Download the CSV

 var res = UrlFetchApp.fetch(link)
 var csvraw = res.getContentText()
 var csv = Utilities.parseCsv(csvraw)
 // Want only columns 0,1,2,3,4,5,6,7,8,9,32,33,34,35,36,37,49,52,53,54,86
 var DesiredCols = [0,1,2,3,4,5,6,7,8,9,10,11,30,31,32,33,34,35,36,37,49,52,53,54,86];

 var Columns = function ExtractCols(arr,indexArr) {
   return arr.map(obj => {
     return obj.filter((ob,index) => {
       if (indexArr.includes(index)) {return ob}
     })
   })
 }

 csv = Columns(csv,DesiredCols)

 var FilterLogic = function(item){
   if(item[1]>2021 && item[9] == 'all'){
     return true;
   } else {
     return false;
   }
 }
 var NewCSV = csv.filter(FilterLogic)
 return NewCSV
}

修改方案:自动转换文本数值为数字类型

问题核心是Utilities.parseCsv()会将CSV中所有内容解析为字符串,需在返回数据前将可转换的数值转为数字类型。添加转换函数遍历处理每个单元格:

function ImportPlayerMPLog(playerID) {
 // Get the Link to the CSV file for player with Player ID Number
 let link = 'https://www.moneypuck.com/moneypuck/playerData/careers/gameByGame/regular/skaters/'
 link += playerID
 link += '.csv'
  // Download the CSV

 var res = UrlFetchApp.fetch(link)
 var csvraw = res.getContentText()
 var csv = Utilities.parseCsv(csvraw)
 // Want only columns 0,1,2,3,4,5,6,7,8,9,32,33,34,35,36,37,49,52,53,54,86
 var DesiredCols = [0,1,2,3,4,5,6,7,8,9,10,11,30,31,32,33,34,35,36,37,49,52,53,54,86];

 var Columns = function ExtractCols(arr,indexArr) {
   return arr.map(obj => {
     return obj.filter((ob,index) => {
       if (indexArr.includes(index)) {return ob}
     })
   })
 }

 csv = Columns(csv,DesiredCols)

 // 新增数值转换函数
 const convertToNumbers = (arr) => {
   return arr.map(row => {
     return row.map(cell => {
       const num = parseFloat(cell);
       return isNaN(num) ? cell : num;
     });
   });
 };

 // 转换数值类型
 csv = convertToNumbers(csv);

 var FilterLogic = function(item){
   if(item[1]>2021 && item[9] == 'all'){
     return true;
   } else {
     return false;
   }
 }
 var NewCSV = csv.filter(FilterLogic)
 return NewCSV
}

关键修改说明

  • convertToNumbers函数:遍历每一行的每个单元格,用parseFloat尝试转换为数字。若转换结果不是NaN(即有效数值)则返回数字,否则保留原文本
  • 在提取目标列后、过滤数据前调用该函数,确保返回的数组中数值类型数据以数字格式存在

修改后导入Google Sheets的数值会自动识别为数字类型,无需再用arrayformula手动转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:28:27