[英]How to remove decimal separator if the decimal part is zero?
I'm using ClosedXML to create a excel spreadsheet. 我正在使用ClosedXML创建一个Excel电子表格。 The issue takes place while formatting cells, containg percentages. 该问题发生在格式化包含百分比的单元格时。
The format I came up to is 0.##%
. 我想到的格式是0.##%
。
It works well when the decimal part is not zero, it shows: 1,15%
; 当小数部分不为零时,它会很好地显示: 1,15%
; but when it's integral-valued, it leaves the decimal separator visible, while hiding zeroes, for example: 5,%
. 但是,当它是整数时,它将保留小数点分隔符,同时隐藏零,例如: 5,%
。
How can I make it hide the decimal separator as well? 如何使其也隐藏小数点分隔符?
Here is a small program, demonstrating the issue: 这是一个演示该问题的小程序:
XLWorkbook wb = new XLWorkbook();
var ws = wb.AddWorksheet("test");
string format = "0.##%";
var cell = ws.Cell(1, 1);
cell.SetValue(5.2M / 100);
cell.Style.NumberFormat.Format = format;
cell = ws.Cell(1, 2);
cell.SetValue(5M / 100);
cell.Style.NumberFormat.Format = format;
wb.SaveAs("test.xlsx");
and the output is 输出是
Many thanks to Jason for the link to CLOSED XML: Conditional Formatting ! 非常感谢Jason链接到CLOSED XML:条件格式 !
Thanks to this I managed to find the way to apply conditional formatting I needed: 由于这一点,我设法找到了应用所需的条件格式的方法:
cell.AddConditionalFormat()
.WhenEquals(
string.Format(
"=TRUNC(${0}${1})",
cell.WorksheetColumn().ColumnLetter(),
cell.WorksheetRow().RowNumber()))
.NumberFormat
.Format = "general\"%\"";
I gave up using percent format specifier, as it makes me divide by 100. From Excel Custom Number Formats : 我放弃使用百分比格式说明符,因为它使我除以100。从Excel自定义数字格式 :
% Percentage. 百分比百分比。 Microsoft Excel multiplies by 100 and adds the % character. Microsoft Excel乘以100并添加%字符。
Now I simply add %
as a string, not as a format specifier. 现在,我只是将%
添加为字符串,而不是格式说明符。
So the main number format is 0.##\\"%\\"
, but when the value's decimal part is zero, I substitute the number format to the general one with %
in the end using conditional formatting. 因此,主要数字格式为0.##\\"%\\"
,但是当值的小数部分为零时,我将使用条件格式将数字格式最终替换为带有%
的通用数字格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.