В настоящее время я пытаюсь манипулировать последними импортированными данными CSV из GMail на основе следующего кода:
function importCSVFromGmail() {
//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('PFC Redemption Limit').getThreads(0,1);
// var messages = threads[0].getMessages();
// var message = messages[threads.getMessageCount()-1];
// var attachment = message.getAttachments()[0];
// Use length of the object to index last item
var first_thread = threads[0].getMessages();
var last_thread = threads[threads.length-1].getMessages();
// Only use last thread:
var last_thread_last_message = last_thread[last_thread.length-1];
var attachment = last_thread_last_message.getAttachments()[0];
// Is the attachment a CSV file
if (attachment.getContentType() === "text/csv") {
var ss = SpreadsheetApp.getActive();
var sh = SpreadsheetApp.openById('xx').getSheetByName("Redemption Data")
//parses content of csv to array
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
// Remember to clear the content of the sheet before importing new data
sh.clearContents().clearFormats();
//pastes array to sheet
sh.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
//marks the Gmail message as read and unstars it (Filter sets a star)
last_thread_last_message.markRead();
last_thread_last_message.unstar();
//The code formats the code so it can be entered into the Google Script
function CSVToArray( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
// Return the parsed data.
return( arrData );
}}}}}
Я думаю, что это может работать двумя способами: 1. Добавить скрипт для вычисления коэффициента погашения (однако он не работает с приведенным выше кодом.)
var spreadsheet = SpreadsheetApp.openById('xx');
spreadsheet.getRange('AH1').activate();
spreadsheet.getCurrentCell().setValue('Redemption Rate');
spreadsheet.getRange('AH2').activate();
spreadsheet.getCurrentCell().setFormula('=K2/G2');
spreadsheet.getActiveRange().autoFillToNeighbor(SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
var currentCell = spreadsheet.getCurrentCell();
spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
currentCell.activateAsCurrentCell();
spreadsheet.getRange('AH2:AH').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
spreadsheet.getRange('AH2:AH').setNumberFormat('0.00%');
Чтобы добавить формулу к существующему листу -> Как импортировать данные CSV в лист Google, не затрагивая часть листа Google?
Это мой первый вопрос по stackoverflow.
Спасибо !!