2015-10-04 31 views
-1

我將2列數據插入到Google電子表格中。我的表有3列A,B和C.列A,B數據通過表單插入,但列C數據通過公式= HTTPResponse()插入。如何使用以下代碼將新公式的數據插入到窗體C的新行上?目前我的代碼不會將代碼複製到新行!如何在向Google表格插入新行後應用最後一行的函數/公式?

插入的代碼:

function doPost(e) { 
    var ss = SpreadsheetApp.openById(ScriptProperties.getProperty('active')); 
    var sheet = ss.getSheetByName("DATA"); 
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; //read headers 
    var nextRow = sheet.getLastRow(); // get next row 
    var cell = sheet.getRange('a1'); 
    var col = 0; 


for (i in headers){ 
    if (headers[i] == "Timestamp"){ 
     val = new Date(); 
    } else if (headers[i] == "HTTPResponse"){ // (based on the assumption you add a column to you sheet with this name 
     val = '=HTTPResponse(B'+(nextRow+1)+')'; 
    } else { 
     val = e.parameter[headers[i]]; 
    } 
    cell.offset(nextRow, col).setValue(val); 
    col++; 
    } 

    var app = UiApp.createApplication(); 
    var panel = app.createVerticalPanel(); 
    for(p in e.parameters){ 
    panel.add(app.createLabel(p +" "+e.parameters[p])); 
    } 
    app.add(panel); 
    return app; 
} 

function setUp() { 
    ScriptProperties.setProperty('active', SpreadsheetApp.getActiveSpreadsheet().getId()); 
} 

//我想應用此下式新的行:

unction HTTPResponse(uri) 
{ 
var response_code ; 
try { 
response_code = UrlFetchApp .fetch(uri) .getResponseCode() .toString() ; 
} 
catch(error) { 
response_code = error .toString() .match(/ returned code (ddd)./)[1] ; 
} 
finally { 
return response_code ; 
} 
} 
+0

您是否嘗試過使用此行「cell.offset(nextRow,col).setValue('= HTTPResponse()');」因爲變量'col'增加了,我認爲你可以在for循環之後添加該行,並且它將在C列中添加公式。檢查它,看看它是如何工作的。 – Gerardo

+0

感謝您的回覆。我在cell.offset(nextRow,col).setValue(val);我在C列中獲得了「未定義」的值!我該如何解決這個問題? – user1788736

+0

你還加了一個url嗎?函數HTTPResponse需要一個URL,因此它可以使用URLFecht.fetch函數調用它。 – Gerardo

回答

0

代碼的邏輯是循環通過片標題,以匹配通過參數。如果未找到列標題,則valundefined。該解決方案將是具有針對式命名列,並創建一個類似的時間戳如另一個異常:

for (i in headers){ 
    if (headers[i] == "Timestamp"){ 
     val = new Date(); 
    } else if (headers[i] == "HTTPResponse"){ // (based on the assumption you add a column to you sheet with this name 
     val = '=HTTPResponse(B'+(nextRow+1)+')'; 
    } else { 
     val = e.parameter[headers[i]]; 
    } 
    cell.offset(nextRow, col).setValue(val); 
    col++; 
    } 

如果出於性能考慮,您更願意跑HTTPResponse()當一個新的值將被提交,並返回一個靜態值而不是變量val設置爲一個公式您可以通過替換線得到HTTPResponse()值:

// assuming that url is the name of the POST value with the url 
    val = HTTPResponse(e.parameter.url); 

這裏是a Google Sheet which implements both methods副本(文件>製作副本,看開工具>腳本編輯器)

+0

感謝您的回覆。我按照你的建議命名C列爲HTTPResponse,並使用你發佈的代碼 ,當數據被插入到行中時,我仍然在新行(列C)中得到了udefined! 有沒有從表格單元格,但從後 方法的url(在谷歌腳本內)的refrence值,並運行httresponse並將其值列c列?有沒有其他方法可以解決這個問題? – user1788736

+0

@ user1788736我已經更新了答案,包括如何將靜態值導入單元格以及實現兩種方法的示例Google Sheet(請記住文件>製作副本以查看工具>腳本編輯器代碼) – mhawksey

+1

@ user1788736。 。還記得當你更新你的代碼時,你需要發佈一個新版本或者應用程序不會使用你的編輯,除非在開發模式下 – mhawksey

相關問題