是否可以通过编程方式将RTF文件转换为gdocs,或者如果无法转换,则只需复制内容?我有数百个存储在gdrive中,所以我希望将它们转换为使其更易于操作和稍后合并。
答案 0 :(得分:2)
如果我的理解是正确的,那么该示例脚本如何?
作为简单的转换,您可以使用高级Google服务的Drive.Files.copy({mimeType: MimeType.GOOGLE_DOCS}, fileId)
脚本。但是从您的问题来看,我认为当转换许多文件时,执行时间可能超过6分钟。因此,在此示例脚本中,我使用批处理请求将文件与Drive API的files.copy方法进行了收敛。
运行脚本时,请将参数设置为main()
的功能。并运行main()
。
// Get file IDs of Microsoft Excel files in a specific folder including subfolders.
function getFileIds(folder, fileIds, q) {
var files = folder.searchFiles(q);
while (files.hasNext()) {
fileIds.push(files.next().getId());
}
var folders = folder.getFolders();
while (folders.hasNext()) {
getFileIds(folders.next(), fileIds, q);
}
return fileIds;
}
// Convert Microsoft Docs to Google Docs
function convertToGoogleDocs(fileIds, dest, to) {
var limit = 100;
var split = Math.ceil(fileIds.length / limit);
var reqs = [];
for (var i = 0; i < split; i++) {
var boundary = "xxxxxxxxxx";
var payload = fileIds.splice(0, limit).reduce(function(s, e, i) {
s += "Content-Type: application/http\r\n" +
"Content-ID: " + i + "\r\n\r\n" +
"POST https://www.googleapis.com/drive/v3/files/" + e + "/copy" + "\r\n" +
"Content-Type: application/json; charset=utf-8\r\n\r\n" +
JSON.stringify({"parents": [dest], "mimeType": to}) + "\r\n" +
"--" + boundary + "\r\n";
return s;
}, "--" + boundary + "\r\n");
var params = {
method: "post",
contentType: "multipart/mixed; boundary=" + boundary,
payload: payload,
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
var req = UrlFetchApp.getRequest("https://www.googleapis.com/batch/drive/v3", params);
reqs.push(req);
}
return UrlFetchApp.fetchAll(reqs);
}
// Please run this function.
function main() {
var sourceFolderId = "###"; // Folder ID including source files. Please set this.
var destinationFolderId = "###"; // Folder ID that the converted files are put. Please set this.
var from = [MimeType.RTF, MimeType.MICROSOFT_WORD_LEGACY]; // Source mimeType
var to = MimeType.GOOGLE_DOCS; // Destination mimeType
var q = from.reduce(function(q, e, i) {return q += "mimeType='" + e + "'" + (i < from.length - 1 ? " or " : "")}, "");
var fileIds = getFileIds(DriveApp.getFolderById(sourceFolderId), [], q);
Logger.log(fileIds)
var res = convertToGoogleDocs(fileIds, destinationFolderId, to);
Logger.log(res);
}
application/msword
。因此我同时搜索了application/rtf
和application/msword
。如果我误解了您的问题,而这不是您想要的结果,我深表歉意。