You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script:如何通过getFileByID获取文件并设置指定文件类型

解决Google Apps Script邮件附件自动转PDF问题(生成Tab分隔文本格式)

要满足团队OMS的订单上传要求,直接从云端硬盘获取的Google表格Blob在邮件发送时会自动转为PDF,正确的做法是直接导出Tab分隔的文本格式Blob,无需保存到云端硬盘,直接用于邮件附件。

修改后的核心代码

// 获取数据表ID
var orderUploadResponse = items[1].getResponse();
// 格式化时间作为文件名
var timeFormatted = Utilities.formatDate(time, "CDT", "'MNL'-MMddyyyy-hhmm");

var fileSheetBlob;
try {
  // 打开目标表格
  var spreadsheet = SpreadsheetApp.openById(orderUploadResponse);
  // 构造Tab分隔文本的导出URL
  var exportUrl = spreadsheet.getUrl().replace(/\/edit.*$/, '') + '/export?exportFormat=txt&sep=%09';
  // 带上授权信息获取Blob
  var response = UrlFetchApp.fetch(exportUrl, {
    headers: {
      'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
    }
  });
  // 设置Blob的MIME类型和文件名
  fileSheetBlob = response.getBlob()
    .setContentType('text/tab-separated-values')
    .setName(`${timeFormatted}.tsv`);
} catch (err) {
  Logger.log("生成Tab分隔文件失败: " + err);
  // 可选:导出失败时降级为Excel格式附件
  var file = DriveApp.getFileById(orderUploadResponse);
  fileSheetBlob = file.getBlob()
    .setContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    .setName(`${timeFormatted}.xlsx`);
}

// 邮件发送示例
// MailApp.sendEmail({
//   to: '收件人邮箱',
//   subject: '订单上传文件',
//   body: '附件为订单文件',
//   attachments: [fileSheetBlob]
// });

关键说明

  • 直接利用Google Sheets的导出接口,指定exportFormat=txt和sep=%09(制表符的URL编码),确保输出是符合要求的Tab分隔文本格式
  • 通过UrlFetchApp.fetch带上OAuth令牌,避免权限验证问题
  • 生成的Blob直接用于邮件附件,无需调用DriveApp.createFile保存到云端硬盘
  • 保留异常处理逻辑,导出失败时可降级为Excel格式附件(可根据需求调整)

原代码问题分析

原代码中直接修改Drive文件Blob的ContentType无效,因为Google表格的原生Blob是Drive内部格式,并非标准Excel文件,强制修改类型不会改变实际内容结构,导致邮件发送时被自动转为PDF。

内容的提问来源于stack exchange,提问作者Seth Murphy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 00:42:12