Getting value of a cell from google docs spreadsheet into javascript

后端 未结 3 1149
不知归路
不知归路 2020-12-11 18:01

I have a javascript function

function calculate() {
  var interestRate=4.5;
  ...
}

I would like the interestRate to come from a cell in a

3条回答
  •  粉色の甜心
    2020-12-11 18:36

    This is possible, but it's a bit scruffy, despite the cross-site problem.

    The steps are as follows:

    First you need to create a cell within a google spreadsheet that reads the value you want to use, for instance, if the value you want is in cell A1 of the spreadsheet you could put this as a formula in cell B1 as follows:

    ="interestrate="&text(A1,"0.0")&";"
    

    What this does is to create a cell that contains the text(for illustration I've assumed that contained 5.7 as a number):

    interestrate="5.7";
    

    Which is a valid statement in javascript.

    Then you put the following into the head of your html page (or wherever):

    
    

    (obviously putting the key value right for your spreadsheet which contains that new function).

    Now, when the page loads the user's browser will fetch the single line of javascript from the google spreadsheet and execute it. Hence the variable, in this case "interestrate", is set to the value in the original cell (as a string so you'll need to parseFloat this to do calculations).

    This will take a little time so you need to make sure it's operated before your script tries to use the value.

    Also, I suspect this will get VERY slow if you try it with lots of numbers.

    Good luck!

提交回复
热议问题