SmlCellFormatter.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. // Copyright (c) Microsoft. All rights reserved.
  2. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Drawing;
  7. using System.Globalization;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using System.Xml.Linq;
  12. using DocumentFormat.OpenXml.Packaging;
  13. namespace OpenXmlPowerTools
  14. {
  15. public class SmlCellFormatter
  16. {
  17. private enum CellType
  18. {
  19. General,
  20. Number,
  21. Date,
  22. };
  23. private class FormatConfig
  24. {
  25. public CellType CellType;
  26. public string FormatCode;
  27. }
  28. private static Dictionary<string, FormatConfig> ExcelFormatCodeToNetFormatCodeExceptionMap = new Dictionary<string, FormatConfig>()
  29. {
  30. {
  31. "# ?/?",
  32. new FormatConfig
  33. {
  34. CellType = SmlCellFormatter.CellType.Number,
  35. FormatCode = "0.00",
  36. }
  37. },
  38. {
  39. "# ??/??",
  40. new FormatConfig
  41. {
  42. CellType = SmlCellFormatter.CellType.Number,
  43. FormatCode = "0.00",
  44. }
  45. },
  46. };
  47. // Up to four sections of format codes can be specified. The format codes, separated by semicolons, define the
  48. // formats for positive numbers, negative numbers, zero values, and text, in that order. If only two sections are
  49. // specified, the first is used for positive numbers and zeros, and the second is used for negative numbers. If only
  50. // one section is specified, it is used for all numbers. To skip a section, the ending semicolon for that section shall
  51. // be written.
  52. public static string FormatCell(string formatCode, string value, out string color)
  53. {
  54. color = null;
  55. if (formatCode == null)
  56. formatCode = "General";
  57. var splitFormatCode = formatCode.Split(';');
  58. if (splitFormatCode.Length == 1)
  59. {
  60. double dv;
  61. if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out dv))
  62. {
  63. return FormatDouble(formatCode, dv, out color);
  64. }
  65. return value;
  66. }
  67. if (splitFormatCode.Length == 2)
  68. {
  69. double dv;
  70. if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out dv))
  71. {
  72. if (dv > 0)
  73. {
  74. return FormatDouble(splitFormatCode[0], dv, out color);
  75. }
  76. else
  77. {
  78. return FormatDouble(splitFormatCode[1], dv, out color);
  79. }
  80. }
  81. return value;
  82. }
  83. // positive, negative, zero, text
  84. // _("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)
  85. if (splitFormatCode.Length == 4)
  86. {
  87. double dv;
  88. if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out dv))
  89. {
  90. if (dv > 0)
  91. {
  92. var z1 = FormatDouble(splitFormatCode[0], dv, out color);
  93. return z1;
  94. }
  95. else if (dv < 0)
  96. {
  97. var z2 = FormatDouble(splitFormatCode[1], dv, out color);
  98. return z2;
  99. }
  100. else // == 0
  101. {
  102. var z3 = FormatDouble(splitFormatCode[2], dv, out color);
  103. return z3;
  104. }
  105. }
  106. string fmt = splitFormatCode[3].Replace("@", "{0}").Replace("\"", "");
  107. try
  108. {
  109. var s = string.Format(fmt, value);
  110. return s;
  111. }
  112. catch (Exception)
  113. {
  114. return value;
  115. }
  116. }
  117. return value;
  118. }
  119. static Regex UnderRegex = new Regex("_.");
  120. // The following Regex transforms currency specifies into a character / string
  121. // that string.Format can use to properly produce the correct text.
  122. // "[$£-809]" => "£"
  123. // "[$€-2]" => "€"
  124. // "[$¥-804]" => "¥
  125. // "[$CHF-100C]" => "CHF"
  126. static string s_CurrRegex = @"\[\$(?<curr>.*-).*\]";
  127. private static string ConvertFormatCode(string formatCode)
  128. {
  129. var newFormatCode = formatCode
  130. .Replace("mmm-", "MMM-")
  131. .Replace("-mmm", "-MMM")
  132. .Replace("mm-", "MM-")
  133. .Replace("mmmm", "MMMM")
  134. .Replace("AM/PM", "tt")
  135. .Replace("m/", "M/")
  136. .Replace("*", "")
  137. .Replace("?", "#")
  138. ;
  139. var withTrimmedUnderscores = UnderRegex.Replace(newFormatCode, "");
  140. var withTransformedCurrency = Regex.Replace(withTrimmedUnderscores, s_CurrRegex, m => m.Groups[1].Value.TrimEnd('-'));
  141. return withTransformedCurrency;
  142. }
  143. private static string[] ValidColors = new[] {
  144. "Black",
  145. "Blue",
  146. "Cyan",
  147. "Green",
  148. "Magenta",
  149. "Red",
  150. "White",
  151. "Yellow",
  152. };
  153. private static string FormatDouble(string formatCode, double dv, out string color)
  154. {
  155. color = null;
  156. var trimmed = formatCode.Trim();
  157. if (trimmed.StartsWith("[") &&
  158. trimmed.Contains("]"))
  159. {
  160. var colorLen = trimmed.IndexOf(']');
  161. color = trimmed.Substring(1, colorLen - 1);
  162. if (ValidColors.Contains(color) ||
  163. color.StartsWith("Color"))
  164. {
  165. if (color.StartsWith("Color"))
  166. {
  167. var idxStr = color.Substring(5);
  168. int colorIdx;
  169. if (int.TryParse(idxStr, out colorIdx))
  170. {
  171. if (colorIdx < SmlDataRetriever.IndexedColors.Length)
  172. color = SmlDataRetriever.IndexedColors[colorIdx];
  173. else
  174. color = null;
  175. }
  176. }
  177. formatCode = trimmed.Substring(colorLen + 1);
  178. }
  179. else
  180. color = null;
  181. }
  182. if (formatCode == "General")
  183. return dv.ToString(CultureInfo.InvariantCulture);
  184. bool isDate = IsFormatCodeForDate(formatCode);
  185. var cfc = ConvertFormatCode(formatCode);
  186. if (isDate)
  187. {
  188. DateTime thisDate;
  189. try
  190. {
  191. thisDate = DateTime.FromOADate(dv);
  192. }
  193. catch (ArgumentException)
  194. {
  195. return dv.ToString(CultureInfo.InvariantCulture);
  196. }
  197. if (cfc.StartsWith("[h]"))
  198. {
  199. DateTime zeroHour = new DateTime(1899, 12, 30, 0, 0, 0);
  200. int deltaInHours = (int)((thisDate - zeroHour).TotalHours);
  201. var newCfc = cfc.Substring(3);
  202. var s = (deltaInHours.ToString() + thisDate.ToString(newCfc)).Trim();
  203. return s;
  204. }
  205. if (cfc.EndsWith(".0"))
  206. {
  207. var cfc2 = cfc.Replace(".0", ":fff");
  208. var s4 = thisDate.ToString(cfc2).Trim();
  209. return s4;
  210. }
  211. var s2 = thisDate.ToString(cfc, CultureInfo.InvariantCulture).Trim();
  212. return s2;
  213. }
  214. if (ExcelFormatCodeToNetFormatCodeExceptionMap.ContainsKey(formatCode))
  215. {
  216. FormatConfig fc = ExcelFormatCodeToNetFormatCodeExceptionMap[formatCode];
  217. var s = dv.ToString(fc.FormatCode, CultureInfo.InvariantCulture).Trim();
  218. return s;
  219. }
  220. if ((cfc.Contains('(') && cfc.Contains(')')) || cfc.Contains('-'))
  221. {
  222. var s3 = (-dv).ToString(cfc, CultureInfo.InvariantCulture).Trim();
  223. return s3;
  224. }
  225. else
  226. {
  227. var s4 = dv.ToString(cfc, CultureInfo.InvariantCulture).Trim();
  228. return s4;
  229. }
  230. }
  231. private static bool IsFormatCodeForDate(string formatCode)
  232. {
  233. if (formatCode == "General")
  234. return false;
  235. return formatCode.Contains("m") ||
  236. formatCode.Contains("d") ||
  237. formatCode.Contains("y") ||
  238. formatCode.Contains("h") ||
  239. formatCode.Contains("s") ||
  240. formatCode.Contains("AM") ||
  241. formatCode.Contains("PM");
  242. }
  243. }
  244. }