简体   繁体   English

格式化从电子表格中读取的数字

[英]Formatting numbers read from spreadsheet

I'm writing a script that creates fixed-width-text output of the contents of a Google Apps Spreadsheet. 我正在编写一个脚本,用于创建Google Apps电子表格内容的固定宽度文本输出。 I retrieve all the values of the current range using the range.getValues() method, then I loop through everything a couple times and generate a block of text that looks like a nicely-formatted table when pasted into a fixed-width-font email. 我使用range.getValues()方法检索当前范围的所有值,然后我遍历所有内容几次并生成一个文本块,当粘贴到固定宽度字体的电子邮件时,它看起来像一个格式很好的表。

The only issue I'm having is that I cannot replicate the number formatting. 我遇到的唯一问题是我无法复制数字格式。 I can get the number formatting string using range.getNumberFormats() , but I cannot find a method for applying that formatting string within code. 我可以使用range.getNumberFormats()获取数字格式化字符串,但我找不到在代码中应用该格式化字符串的方法。 I tried using the TEXT (value, format) spreadsheet function, but apparently Google Apps Script does not yet support calling spreadsheet functions from within the JavaScript code itself (see this issue for proof). 我尝试使用TEXT(值,格式)电子表格功能,但显然Google Apps脚本还不支持从JavaScript代码本身调用电子表格函数(请参阅此问题以获取证明)。

As of December 2015 , the kludgy work-arounds can be discarded. 截至2015年12月 ,可以放弃kludgy的解决方案。 Google has provided two methods to retrieve the literal string display values from cells. Google提供了两种方法来从单元格中检索文字字符串显示值。 They haven't provided documentation yet, so here's a summary: 他们还没有提供文档,所以这里是一个总结:

Range.getDisplayValue() Range.getDisplayValue()
Returns the display value of the top-left cell in the range, as a String, containing the text value shown on the Sheets UI. 返回范围中左上角单元格的显示值,作为String,包含Sheets UI上显示的文本值。 Empty cells will return an empty string. 空单元格将返回一个空字符串。

Range.getDisplayValues() Range.getDisplayValues()
Returns the rectangular grid of display values for this range. 返回此范围的显示值的矩形网格。 Returns a two-dimensional array of Strings, indexed by row, then by column. 返回一个二维的字符串数组,按行索引,然后按列索引。 Empty cells will be represented by an empty string in the array. 空单元格将由数组中的空字符串表示。 Remember that while a range index starts at 1, 1, the JavaScript array will be indexed from [0][0]. 请记住,当范围索引从1,1开始时,JavaScript数组将从[0] [0]索引。

Example: 例:

Say we have a range in a spreadsheet that we are interested in, like this: 假设我们在电子表格中有一个我们感兴趣的范围,如下所示:

截图

Those four cells include two of the trickiest formats to work around; 这四个单元格包括两种最棘手的格式; date/time and scientific notation. 日期/时间和科学记数法。 But with the new methods, there's nothing to it. 但是使用新方法,没有什么可以做到的。

function demoDisplayValue() {
  var range = SpreadsheetApp.getActiveSheet().getRange("A1:B2");

  Logger.log( range.getDisplayValue() );
  Logger.log( range.getDisplayValues() );
}

Log: 日志:

[16-01-14 13:04:15:864 EST] 1/14/2016 0:00:00
[16-01-14 13:04:15:865 EST] [[1/14/2016 0:00:00, 5.13123E+35], [$3.53, 1,123 lb]]

I found a JavaScript method for setting the number of digits after the decimal point called toFixed(). 我找到了一种JavaScript方法,用于设置小数点后面的位数,称为toFixed()。

Here's the documentation: http://www.w3schools.com/jsref/jsref_tofixed.asp 这是文档: http//www.w3schools.com/jsref/jsref_tofixed.asp

num.toFixed(x) //where x = the number of digits after the decimal point.

My Google Apps script needed to return a message with a dollar value pulled from my spreadsheet. 我的Google Apps脚本需要返回一封邮件,其中包含从我的电子表格中提取的美元值。 It looked terrible with 10 digits after the decimal point. 小数点后10位数看起来很糟糕。 This method applied to my variable solved the problem. 应用于我的变量的这个方法解决了这个问题。 I just added a $ in the text portion of the label. 我刚刚在标签的文本部分添加了$。

Hope this helps! 希望这可以帮助!

The list of pre-supplied formats is here . 预先提供的格式列表在这里 For some formats, a javascript equivalent is relatively straight-forward. 对于某些格式,javascript等价物相对简单。 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. 这是一个屏幕截图,显示了已经复制为html的单元格内容 - 不是像你一样修复的,而是使用电子表格中的格式。

截图

There are Google Apps Script helper functions that make it easier, Utilities.formatString() and Utilities.formatDate() . 有一些Google Apps脚本辅助函数可以使它更容易, Utilities.formatString()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: 对于日期和时间,例如"h:mm:ss am/pm" ,电子表格格式几乎是实用程序所需的 - 我发现您只需要调整某些格式的am / pm指定:

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

For dollars, eg "\\"$\\"#,##0.00" : 对于美元,例如"\\"$\\"#,##0.00"

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

For percent-formatted numbers, eg "0.00%" : 对于百分比格式的数字,例如"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: 对于指数,如"0.000E+00" ,使用内置于toExponential()的javascript,并调整输出看起来更像电子表格:

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... 在电子表格中,这是一个格式问题 - 在脚本中,它更多......

Try the following google apps script 尝试以下谷歌应用程序脚本

function NumberFormat()
{var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];

 var cell = sheet.getRange("A1:B10");
 // Always show 2 decimal points
 cell.setNumberFormat("0,00,000.00");
}

Indeed, you can't call spreadsheet functions directly. 实际上,您无法直接调用电子表格函数。 But you can set the format using setNumberFormats normally. 但您可以正常使用setNumberFormats设置格式。 Take a look at the docs here . 看看这里的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM