csv - 谷歌脚本从 ftp 或谷歌驱动器导入 csv
问题描述
我正在使用脚本从链接导入 csv,但是有一种方法可以将其调整为从 ftp 链接或谷歌驱动器文件导入?谢谢这是我的剧本
function myFunction3() {
// 1. Set the required columns as the column number.
const requiredColumns = [1, 5, 20]; // Please set the required columns. These values are from your question.
// 2. Retrieve CSV data from an URL.
const url = "https://www.stanem.it/csv/InnovaCSV.csv";
const res = UrlFetchApp.fetch(url);
// 3. Convert CSV data to Spreadsheet.
const id = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: "tempSpreadsheet"}, res.getBlob()).id;
// 4. Delete the columns except for the required columns.
const ss = SpreadsheetApp.openById(id);
const sheet = ss.getSheets()[0];
const maxColumn = sheet.getMaxColumns();
const requests = [];
for (let i = 1; i <= maxColumn; i++) {
if (!requiredColumns.includes(i)) {
requests.push({deleteDimension: {range: {sheetId: sheet.getSheetId(), dimension: "COLUMNS", startIndex: i - 1, endIndex: i}}});
}
}
Sheets.Spreadsheets.batchUpdate({requests: requests.reverse()}, id);
// 5. Copy the values of modified CSV data to a sheet in the active Spreadsheet.
const destinationSheetName = "Sheet1"; // Please set the destilnation sheet name in the active Spreadsheet.
const dstss = SpreadsheetApp.getActiveSpreadsheet();
const values = Sheets.Spreadsheets.Values.get(id, sheet.getSheetName()).values;
Sheets.Spreadsheets.Values.update({values: values}, dstss.getId(), destinationSheetName, {valueInputOption: "USER_ENTERED"});
// 6. Remove the temporat Spreadsheet.
DriveApp.getFileById(id).setTrashed(true);
}
解决方案
问题和解决方法:
不幸的是,在当前阶段,无法使用 UrlFetchApp 从 FTP 检索文件。那么在您的情况下,如何从 Google Drive 中检索文件?从 Google Drive 检索 CSV 文件时,修改后的脚本如下。
修改后的脚本:
请按如下方式修改您的脚本。在这个修改后的脚本中,它假设 CSV 文件放在您的 Google Drive 中。
从:// 2. Retrieve CSV data from an URL.
const url = "https://www.stanem.it/csv/InnovaCSV.csv";
const res = UrlFetchApp.fetch(url);
// 3. Convert CSV data to Spreadsheet.
const id = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS, title: "tempSpreadsheet"}, res.getBlob()).id;
至:
// 3. Convert CSV data to Spreadsheet.
const fileId = "### fileId of CSV file on Google Drive ###"; // Please set the file ID of CSV file.
const id = Drive.Files.copy({mimeType: MimeType.GOOGLE_SHEETS, title: "tempSpreadsheet"}, fileId).id;
- 在这种情况下,CSV 文件可以用
Drive.Files.copy
.
参考:
推荐阅读
- c - Kernighan 和 Ritchie 练习 3.4
- user-interface - 如何从两列数据制作一个 Power BI 饼图小部件/或将两个饼图合并为一个
- c# - 如何计算两个波斯日期之间的总天数(以 yyyy/MM 格式)?
- python - 为什么`0--3//2`和`--3//2`之间有区别?
- c# - 我的项目中没有“添加参考”
- typeorm - TypeORM:findOne 在关系上应用了“关系”和“where”条件 - EntityColumnNotFound:未找到实体列
- php - Codeigniter4 显示即使我使用了“set”方法,在运行更新查询时也必须使用“set”方法
- linux - csharp_ls 不适用于 Neovim 内置 lsp
- c# - 可以将 C# 属性序列化为 JSON 吗?
- angular - 使用@ionic/angular 和@capacitor/XXX 的插件/Api 实现之间的区别