diff --git a/OpenXmlFormats/Spreadsheet/Sheet.cs b/OpenXmlFormats/Spreadsheet/Sheet.cs index 3ea11b4c9..b51974cbf 100644 --- a/OpenXmlFormats/Spreadsheet/Sheet.cs +++ b/OpenXmlFormats/Spreadsheet/Sheet.cs @@ -7333,7 +7333,7 @@ public static CT_DataValidation Parse(XmlNode node, XmlNamespaceManager namespac } return ctObj; } - + internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); @@ -7352,9 +7352,9 @@ internal void Write(StreamWriter sw, string nodeName) XmlHelper.WriteAttribute(sw, "sqref", this.sqref); sw.Write(">"); if (this.formula1 != null) - sw.Write(string.Format("", this.formula1)); + sw.Write(string.Format("", XmlHelper.EncodeCDATAContent(this.formula1))); if (this.formula2 != null) - sw.Write(string.Format("", this.formula2)); + sw.Write(string.Format("", XmlHelper.EncodeCDATAContent(this.formula2))); sw.Write(string.Format("", nodeName)); } diff --git a/openxml4Net/Util/XmlHelper.cs b/openxml4Net/Util/XmlHelper.cs index 91eae96df..70f668d91 100644 --- a/openxml4Net/Util/XmlHelper.cs +++ b/openxml4Net/Util/XmlHelper.cs @@ -314,6 +314,7 @@ public static string ExcelDecodeString(string t) } private static readonly char[] xmlEncodeCharsToReplace = { '&', '<', '>', '"' }; + private static readonly char[] cdataEncodeCharsToReplace = { '&', '<', '>','\'' ,'"' }; public static string EncodeXml(string xml) { @@ -330,6 +331,22 @@ public static string EncodeXml(string xml) .Replace("\"", """);//.Replace("'", "'"); } + public static string EncodeCDATAContent(string xml) + { + // quick check whether needed + if(xml.IndexOfAny(cdataEncodeCharsToReplace) == -1) + { + return xml; + } + + return xml + .Replace("&", "&") + .Replace("<", "<") + .Replace(">", ">") + .Replace("\"", """) + .Replace("'", "'"); + } + public static void WriteAttribute(StreamWriter sw, string attributeName, bool value) { WriteAttribute(sw, attributeName, value, true);