我的目标是写一些类似于 File > Download as > *
的内容目前 Google 电子表格中有此功能,但我希望它采用自定义格式。
具体来说,我想将财务交易电子表格转换为 QIF 或 OFX 文件,以便导入到会计软件中。本质上,按下 UI 上的按钮将下载当前打开的电子表格的 QIF/OFX 版本。
到目前为止我已经尝试过以下方法:
- 发布使用
doGet
的服务(通过实现ContentService
)创建自定义文件并使用TextOutput.downloadAsFile()
将其作为下载返回。如果我使用浏览器直接调用端点,则此方法有效。 - 尝试通过 window.location 将浏览器重定向到服务的 URL,但这在应用脚本的上下文中似乎不可用。
- 尝试使用
UrlFetchApp.fetch
让前端(电子表格)让浏览器导航到服务的 URL。这也不起作用(并不奇怪)。
那么,这是正确的方法吗?我还能如何攻击这个?
最佳答案
看起来这就是你必须做的。
- 创建一个 UiApp
- 添加该应用内的下载链接。
- 在电子表格上显示 UiInstance
它有点笨重,但它似乎是最干净的解决方案。
function downloadAsWhatever() {
var app = UiApp.createApplication();
app.add(app.createAnchor("Download the file now!", "https://script.google.com/macros/s/[...]/exec"))
SpreadsheetApp.getActiveSpreadsheet().show(app.setWidth(300).setHeight(150));
}
您可以将应用程序的大小设置为您想要的任何大小。我选择将其设置得更小,以便它在电子表格屏幕上占用更少的空间。
For now the best way to direct a user to a new page is to create an anchor widget and have them click it. We understand that this is not an ideal user experience, but it should suffice for must use cases.
关于javascript - 在 Google Spreadsheets 中编写自定义文件格式下载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14966539/