【发布时间】:2018-11-21 23:41:20
【问题描述】:
我在另一篇帖子Google Apps Script creates sheets version of excel file 中找到了我原来问题的解决方案。
使用答案中提供的代码进行测试我遇到了另一个问题。每次我运行脚本时,它都会再次创建 .xlsx 文件的电子表格版本,即使它们已经存在。我尝试使用最后一个 If 修改代码,但没有结果。然后返回运行您发布的代码,以防我遗漏了某些内容,但它会不断创建相同文件的版本。
任何关于我可以做些什么来解决这个问题的想法将不胜感激。
他回答中提供的代码如下。
// Convert the user's stored excel files to google spreadsheets based on the specified directories.
// There are quota limits on the maximum conversions per day: consumer @gmail = 250.
function convertExcelToGoogleSheets()
{
var user = Session.getActiveUser(); // Used for ownership testing.
var origin = DriveApp.getFolderById("origin folder id");
var dest = DriveApp.getFolderById("destination folder id");
// Index the filenames of owned Google Sheets files as object keys (which are hashed).
// This avoids needing to search and do multiple string comparisons.
// It takes around 100-200 ms per iteration to advance the iterator, check if the file
// should be cached, and insert the key-value pair. Depending on the magnitude of
// the task, this may need to be done separately, and loaded from a storage device instead.
// Note that there are quota limits on queries per second - 1000 per 100 sec:
// If the sequence is too large and the loop too fast, Utilities.sleep() usage will be needed.
var gsi = dest.getFilesByType(MimeType.GOOGLE_SHEETS), gsNames = {};
while (gsi.hasNext())
{
var file = gsi.next();
if(file.getOwner().getEmail() == user.getEmail())
gsNames[file.getName()] = true;
}
// Find and convert any unconverted .xls, .xlsx files in the given directories.
var exceltypes = [MimeType.MICROSOFT_EXCEL, MimeType.MICROSOFT_EXCEL_LEGACY];
for(var mt = 0; mt < exceltypes.length; ++mt)
{
var efi = origin.getFilesByType(exceltypes[mt]);
while (efi.hasNext())
{
var file = efi.next();
// Perform conversions only for owned files that don't have owned gs equivalents.
// If an excel file does not have gs file with the same name, gsNames[ ... ] will be undefined, and !undefined -> true
// If an excel file does have a gs file with the same name, gsNames[ ... ] will be true, and !true -> false
if(file.getOwner().getEmail() == user.getEmail() && !gsNames[file.getName()])
{
Drive.Files.insert(
{title: file.getName(), parents: [{"id": dest.getId()}]},
file.getBlob(),
{convert: true}
);
// Do not convert any more spreadsheets with this same name.
gsNames[file.getName()] = true;
}
}
}
}
【问题讨论】:
-
为了正确了解您的情况,请问您想做什么?您想将
origin文件夹中的 Excel 文件转换为 Google 电子表格,并将转换后的电子表格放入dest文件夹。此时,当转换文件的文件名存在于dest文件夹中时,您不想转换它。我的理解正确吗? -
是的,Excel 文件已上传到 Origin 文件夹,脚本会在 Destination 文件夹中创建 Google 电子表格版本。该脚本将在一天内运行多次,因为更多文件不断上传到原始文件夹。该脚本旨在转换 Dest 文件夹中还没有电子表格版本的 Excel 文件,但它会继续为所有文件创建版本,即使它们之前已经有脚本创建的电子表格版本。
-
感谢您的回复。我发布了修改脚本的答案。你能确认一下吗?如果那不是你想要的,请告诉我。我想修改它。
标签: excel google-apps-script google-sheets google-drive-api