Google Apps Script写入Spreadsheet时Player ID格式异常求助
解决Google Sheets中Player ID自动转换格式的问题
方案1:给Player ID添加单引号前缀
Google Sheets会将以单引号开头的内容强制识别为文本,且单引号不会在单元格中显示。在提取Player ID后直接拼接单引号即可:
function getPlayerData() { // 省略获取leagueInfo接口数据的代码... const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerData"); let row = 1; // 起始行 for (const playerInfo of leagueInfo.playerInfo) { // 给ID添加单引号前缀,强制文本格式 const formattedId = "'" + playerInfo.playerId; const eligiblePos = playerInfo.eligiblePos; // 写入工作表 sheet.getRange(row, 1).setValue(formattedId); sheet.getRange(row, 2).setValue(eligiblePos); row++; } }
方案2:先设置单元格格式为文本再写入
先将存储Player ID的列设置为纯文本格式,再写入数据,避免Sheets自动解析格式:
function getPlayerData() { // 省略获取leagueInfo接口数据的代码... const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerData"); // 将A列(假设存Player ID)设置为文本格式 sheet.getRange("A:A").setNumberFormat("@"); let row = 1; for (const playerInfo of leagueInfo.playerInfo) { sheet.getRange(row, 1).setValue(playerInfo.playerId); sheet.getRange(row, 2).setValue(playerInfo.eligiblePos); row++; } }
方案3:批量写入时确保数据为字符串类型(高效处理大量数据)
如果需要批量写入多条数据,先将Player ID转为字符串,同时设置目标区域的格式为文本:
function getPlayerData() { // 省略获取leagueInfo接口数据的代码... const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PlayerData"); const playerData = []; // 整理数据,确保Player ID为字符串类型 leagueInfo.playerInfo.forEach(info => { playerData.push([ String(info.playerId), // 强制转为字符串 info.eligiblePos ]); }); // 设置目标区域格式为文本 const targetRange = sheet.getRange(1, 1, playerData.length, 2); targetRange.setNumberFormat("@"); // 批量写入数据 targetRange.setValues(playerData); }
注意:如果之前已经写入过被错误转换的数据,需要先清空对应单元格,再按上述方法重新写入,否则修改格式后已转换的数据无法恢复原始ID。
内容的提问来源于stack exchange,提问作者mika_972
相关产品推荐
相关产品推荐

