如何在电子邮件中发送谷歌工作表数据,保持python的格式(颜色)不变



我有一个要求,我必须在电子邮件中以表格的形式发送谷歌工作表数据,其中包含工作表中的所有颜色格式。

以前,我从工作表中读取数据,加载panda数据框,然后在那里应用颜色编码。由于我在谷歌表单中生成了许多需要通过电子邮件发送的报告,所以这是不可行的。想知道这是否可以使用谷歌API完成?也不能考虑延期。

我相信这可以通过Google API完成,因为您可以使用HTTP请求GET https://www.googleapis.com/drive/v3/files/fileId/export将任何工作表导出为html格式

检查此链接:https://developers.google.com/drive/api/v3/reference/files/export

您可以在该页面上测试它,只需传递您的文档的id并将mime类型指定为application/zip,即可将您的工作表设置为压缩的html。有关其他已批准的mime类型,请参见此处:https://developers.google.com/drive/api/v3/ref-export-formats

您可以通过以下脚本来完成

function sendEmail() {
MailApp.sendEmail({to:'somebody@gmail.com',
subject: 'my subject', 
htmlBody: tableHTML()})
};
function tableHTML(){
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
var plage = sh.getDataRange()
var data = plage.getDisplayValues()
var taille = plage.getFontSizes()
var fond = plage.getBackgrounds()
var couleur = plage.getFontColors()
var police = plage.getFontFamilies()
var htmltable = '<table style="border:1px solid #CCC;border-collapse:collapse;">';
for (row = 0; row<data.length; row++){
htmltable += '<tr>';
for (col = 0 ;col<data[row].length; col++){
if (data[row][col] === "" || 0) {htmltable += '<td>' + '&nbsp;' + '</td>';} 
else
htmltable += '<td style="border:1px solid #CCC; font-family:' + police[row][col] + '; background-color:' + fond[row][col] + '; color:' + couleur[row][col] + '; font-size:' + taille[row][col] + 'px;">' + data[row][col] + '</td>';
}
htmltable += '</tr>';
}
htmltable += '</table>';
return htmltable
}

这是可行的。您所需要做的就是在身份验证时指定正确的范围,https://spreadsheets.google.com/feedshttps://docs.google.com/feedshttps://www.googleapis.com/auth/drive.file


首先,让我们看看一个带有";任何有链接的人";权限。我们将从浏览器窗口调用API。

–从Google开发者控制台获取您的API密钥(创建应用程序,允许其访问Drive API并生成API密钥。(

–获取权限设置为"的谷歌电子表格的文件ID;任何有链接的人";。

现在将此地址粘贴到您的浏览器中,以获得一个html格式的工作表和一个css文件的zip存档:https://www.googleapis.com/drive/v3/files/{FILE_ID}/export?mimeType=application%2Fzip&key={YOUR API KEY}记住用您的file_ID和API_KEY填充地址。


现在让我们使用curl和OAuth身份验证对私有文件执行同样的操作

0.从Google开发人员控制台准备您的API_KEY、CLIENT_ID和CLIENT_SECRET。


1.验证设备并获取device_CODE

curl 
-d 'client_id=[CLIENT_ID]' 
-d 'scope=https://spreadsheets.google.com/feeds https://docs.google.com/feeds https://www.googleapis.com/auth/drive.file' 
https://oauth2.googleapis.com/device/code

2.转到验证urlhttps://www.google.com/device


3.获取ACCESS_TOKEN

curl -d client_id=[CLIENT_ID] 
-d client_secret=[CLIENT_SECRET] 
-d device_code=[DEVICE_CODE] 
-d grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code 
https://accounts.google.com/o/oauth2/token

3.或者刷新令牌

curl 
--request POST 
--data 'client_id=[CLIENT_ID]' 
--data 'client_secret=[CLIENT_SECRET]' 
--data 'refresh_token=[REFRESH_TOKEN]' 
--data 'grant_type=refresh_token' 
https://accounts.google.com/o/oauth2/token

4.并获取您的文件

curl 
-H 'Authorization: Bearer [ACCESS_TOKEN]' 
-H 'Accept: application/json' 
https://www.googleapis.com/drive/v3/files/[FILE_ID]/export?mimeType=application%2Fzip&key=[API_KEY]

最新更新