使用Drive API3将CSV转为Google Sheets时如何禁用自动格式转换
解决方案
问题原因
你当前使用Drive.Files.copy直接转换文件格式的方案,默认会触发Google Drive内置的自动类型转换逻辑,且该接口没有提供关闭转换的配置项,因此无法避免日期、数字、公式的自动识别。
前置操作
首先需要在你的Apps Script项目中启用Google Sheets API高级服务:
- 打开脚本编辑器,点击左侧「服务」栏的+按钮
- 在列表中找到「Google Sheets API」,选中后点击「添加」即可
可直接使用的代码
function convertCsvToSheetsWithoutAutoConvert() { // 替换为你的CSV文件ID const CSV_FILE_ID = '1234'; // 读取CSV原始文本内容 const csvFile = DriveApp.getFileById(CSV_FILE_ID); const csvContent = csvFile.getBlob().getDataAsString(); // 获取CSV所在的父文件夹ID,生成的Sheets会存在同一个位置 const parentFolderId = csvFile.getParents().next().getId(); // 新建空白Google Sheets文件 const newSheet = SpreadsheetApp.create('导入后的表格'); const newFile = DriveApp.getFileById(newSheet.getId()); newFile.moveTo(DriveApp.getFolderById(parentFolderId)); const spreadsheetId = newSheet.getId(); // 调用Sheets API写入CSV内容,禁用自动类型转换 Sheets.Spreadsheets.batchUpdate({ requests: [{ pasteData: { coordinate: { sheetId: newSheet.getSheets()[0].getSheetId(), rowIndex: 0, columnIndex: 0 }, data: csvContent, type: 'PASTE_NORMAL', delimiter: ',', // 核心参数:禁用自动转数字、日期、公式,对应你要的菜单勾选效果 disableAutomaticConversion: true } }] }, spreadsheetId); }
效果说明
上述代码中disableAutomaticConversion: true参数完全对应Google Sheets菜单导入时「取消勾选将文本转换为数字、日期和公式」的效果,你示例中的2021-25-03这类内容会原样保留为文本格式,不会被识别转换为日期。
内容的提问来源于stack exchange,提问作者Whoz
相关产品推荐
相关产品推荐

