使用openxlsx设置单引号为千位分隔符的格式问题求助
解决openxlsx中用单引号做千位分隔时小数字误加单引号的问题
我尝试用R的openxlsx包,通过createStyle设置数字格式,实现以单引号作为千位分隔符的效果,最初用的样式代码是:
fmt_mil0 <- createStyle(numFmt = "#'##0", halign = "right")
但这个格式会给小于1000的数字(比如20变成'20)也添加单引号,试了反引号、重音符号等格式都无效,测试代码如下:
library(openxlsx) wb <- createWorkbook() df <- c(1000, 20, -20, -0.1) fmt_mil <- createStyle(numFmt = "#'##0", halign = "right") fmt_mil1 <- createStyle(numFmt = "#`##0", halign = "right") fmt_mil2 <- createStyle(numFmt = "#´##0", halign = "right") addWorksheet(wb, "test") writeData(wb, "test", df) writeData(wb, "test", df, startCol = 2) writeData(wb, "test", df, startCol = 3) addStyle(wb, "test",style = fmt_mil, rows = 1:4, cols =1, gridExpand = TRUE, stack = TRUE) addStyle(wb, "test",style = fmt_mil1, rows = 1:4, cols =2, gridExpand = TRUE, stack = TRUE) addStyle(wb, "test",style = fmt_mil2, rows = 1:4, cols =3, gridExpand = TRUE, stack = TRUE) saveWorkbook(wb, "test.xlsx", overwrite = TRUE)
解决思路
问题根源是Excel自定义格式规则:#'##0会给所有数字的最高位前强制添加单引号,而非仅作为千位分隔符使用。要实现仅对≥1000或≤-1000的数字显示单引号千位分隔,小数字正常显示,需利用Excel格式的条件分支语法(方括号定义条件,分号分隔不同场景):
正确的样式定义代码如下:
fmt_mil_fix <- createStyle(numFmt = "[>=1000]#\\'##0;[<=-1000]\\-#\\'##0;0", halign = "right")
[>=1000]#\\'##0:对≥1000的正数,用单引号作为千位分隔(R中需用\\'转义单引号)[<=-1000]\\-#\\'##0:对≤-1000的负数,保留负号并添加单引号千位分隔0:对-999到999之间的数字,直接显示原数字(若需保留小数,可改为0.00等格式)
测试验证代码
library(openxlsx) wb <- createWorkbook() df <- c(1000, 20, -20, -0.1, 123456, -7890) # 修复后的样式 fmt_mil_fix <- createStyle(numFmt = "[>=1000]#\\'##0;[<=-1000]\\-#\\'##0;0", halign = "right") addWorksheet(wb, "test") writeData(wb, "test", df) addStyle(wb, "test", style = fmt_mil_fix, rows = 1:length(df), cols = 1, gridExpand = TRUE, stack = TRUE) saveWorkbook(wb, "test_fix.xlsx", overwrite = TRUE)
运行后对应显示效果:
- 1000 → 1'000
- 20 → 20
- -20 → -20
- -0.1 → 0(如需保留小数,可将格式最后段改为
0.0) - 123456 → 123'456
- -7890 → -7'890
内容的提问来源于stack exchange,提问作者arnyeinstein
相关产品推荐
相关产品推荐

