Google スプレッドシートの Excel バージョンを電子メールで送信するためのアプリ スクリプトを作成したいと考えています。スプレッドシートを Excel ファイルとして保存できることはわかっています。スクリプトを使用して Excel バージョンを添付ファイルとして電子メールで送信できるかどうかはわかりません。これはどのように行うことができますか?
5 に答える
別の最近の投稿( Thomas van Latum ) での回答の後、提案された doc api を試してみたところ、興味深い結果が得られました...これが私が使用したテスト コードであり、ファイルが xls ではなく xlsx 形式であることを除いて、うまく機能しています。しかし、これは最近では必ずしも問題ではありません:
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
function test(){
var id = 'spreadsheet_ID'
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
googleOAuth_('docs',url)).getBlob()
DocsList.createFile(doc).rename('newfile.xls')
}
Export.xlsx
注:名前を変更しない場合、デフォルト名は
var xlsfileID = DocsList.createFile(doc).getId()
EDIT : 認証プロセスをトリガーするには、このような小さな関数を試して、スクリプト エディターから実行します
function autorise(){
// function to call to authorize googleOauth
var id=SpreadsheetApp.getActiveSpreadsheet().getId();
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
googleOAuth_('docs',url)).getContentText();
}
Rumpelstiltskin をプレイするのに約 4 時間費やしたのは、古いスプレッドシート バージョンの非常に古いコード スニペットや、「google docs script send Excel attachment」などをグーグルで検索したときに見つかる古い OAUTH がないためです (つまり、既存のスプレッドシート、Excel形式に変換してメールの添付ファイルとして送信)実際に機能し、最終的に解決策を見つけました.
実際の添付コンテンツを作成するために、想定される res.getContent() も res.getBlob() も res.getBytes だけでも機能しませんでした。これらのヒントは誤解を招くものです。
私にとって唯一うまくいくのは、response.getBlob().getContent()! だけです。
コード全体:
function sendCurrentDocAsEmail() {
var driveService = getDriveService();
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
var email = "recipient@demo.com"
var subject = "Here be Subjects";
var body = "Don't even think about learning how to code. It's wasted time.";
var file = Drive.Files.get(ssID );
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
});
var attachments = [{
fileName:sheetName+".xlsx",
content: response.getBlob().getBytes(), // this single line has cost me hours!
mimeType:"application//xls",
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
}];
MailApp.sendEmail(email,subject ,body, {attachments:attachments});
}
getDriveService() は、https: //github.com/googlesamples/apps-script-oauth2 の Google の「OAuth2 for Apps Script」readme の関数です。
最新の作業バージョンは以下です。この例に基づいて、つまり、前の回答と似ていますが、トークンを受け取るために人間がリンクを経由する必要のない Google サービス アカウントを使用します。Google から Oath ライブラリをインストールする必要があります。手順は非常に明確です。
var PRIVATE_KEY = 'xxx'
var CLIENT_EMAIL = 'xxx';
var USER_EMAIL=Session.getActiveUser().getEmail()
function getOathService() {
return OAuth2.createService('GoogleDrive:' + USER_EMAIL)
// Set the endpoint URL.
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the private key and issuer.
.setPrivateKey(PRIVATE_KEY)
.setIssuer(CLIENT_EMAIL)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject(USER_EMAIL)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope('https://www.googleapis.com/auth/drive');
}
function sendEmail() {
var oathService = getOathService();
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var file = Drive.Files.get(ssID );
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var file = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + oathService.getAccessToken()
}
});
var attachments = [{
fileName:'xxx.xls',//TODO DATE
content: file.getBlob().getBytes(),
mimeType:"application//xls",
headers: {
Authorization: 'Bearer ' + oathService.getAccessToken()
}
}];
MailApp.sendEmail('email@domain.com', 'xxx', 'Hi,\n\nPlease see the last data in attachment',{attachments:attachments});
}
ニーズに合わせて変更した後、次のコード スニペットを使用します。
var file = DocsList.getFileById(FILE_ID);
var attachment = file.getAs('application/vnd.ms-excel');
MailApp.sendEmail("abcd@example.com", "Subject", " Body" , {"fileName": "Your_file_name" , "mimeType" : "application/vnd.ms-excel" , "content":attachment.getBytes() } );
このコードはテストされていないことに注意してください。ポップアップする可能性のあるエラーを 1 つまたは 2 つ修正してください。