Formatting numbers read from spreadsheet

前端 未结 5 567
终归单人心
终归单人心 2020-12-14 21:45

I\'m writing a script that creates fixed-width-text output of the contents of a Google Apps Spreadsheet. I retrieve all the values of the current range using the range

5条回答
  •  天命终不由人
    2020-12-14 22:11

    The list of pre-supplied formats is here. For some formats, a javascript equivalent is relatively straight-forward. For others, it's extremely difficult. And handling user-defined custom formats - good luck with that.

    Here's a screenshot showing cell content that has been replicated as html - not fixed, as you are doing, yet using the formats from the spreadsheet.

    Screenshot

    There are Google Apps Script helper functions that make it easier, Utilities.formatString() and Utilities.formatDate().

    For dates & times, like "h:mm:ss am/pm", the spreadsheet formats are almost what is needed for the utility - I've found that you just need to tweak the am/pm designation for some formats:

      var format = cell.getNumberFormat();
      var jsFormat = format.replace('am/pm','a');
      var jsDate = Utilities.formatDate(
              date,
              this.tzone,
              jsFormat);
    

    For dollars, e.g. "\"$\"#,##0.00":

      var dollars = Utilities.formatString("$%.2f", num);
    

    For percent-formatted numbers, e.g. "0.00%":

      var matches = format.match(/\.(0*?)%/);
      var fract = matches ? matches[1].length : 0;     // Fractional part
      var percent = Utilities.formatString("%.Xf%".replace('X',String(fract)), 100*num);
    

    For exponentials, like "0.000E+00", utilize the javascript built-in toExponential(), and tweak the output to look more like the spreadsheet:

    if (format.indexOf('E') !== -1) {
      var fract = format.match(/\.(0*?)E/)[1].length;  // Fractional part
      return num.toExponential(fract).replace('e','E');
    }
    

    You can just do a string comparison against the stored spreadsheet formats to pick the right converter.

    And what do I mean by extremely difficult? Try to get a formatter that comes up with the exact same numerator and denominator choices Sheets makes for # ?/? and # ??/??! In the spreadsheet, it's a matter of formatting - in a script, it's much more...

提交回复
热议问题