【发布时间】:2016-10-27 12:41:23
【问题描述】:
我需要一些关于字符串格式化和转义的帮助。 从这个字符串格式开始:
string.Format("=IF(OR({0}="";{1]="");"";{0}-{1})", cell1, cell2)
我正在尝试获取这个字符串:
=IF(OR(L2="";M2="");"";L2-M2)
这是我需要作为 Excel 公式插入的字符串。我试过string.Format,我试过@"...",我什至尝试过连接字符串并转义引号。
无论我尝试什么,我总是得到这个字符串:
=IF(OR(L2=\"\";M2=\"\");\"\";L2-M2)
当我尝试打开它时,这会破坏我的 Excel 文件。我不明白为什么\留在那里。
欢迎任何提示。谢谢。
int atCol = ws.Dimension.End.Column + 1;
//insert the header
ws.Cells[1, atCol].Value = "Diff. Quote letzte 2 Jahre";
ws.Cells[1, atCol].Style.WrapText = true;
for (int i = 2; i<=ws.Dimension.End.Row; i++)
{
var cell1 = ws.Cells[i, atCol + 1].Address;
var cell2 = ws.Cells[i, atCol + 2].Address;
//ws.Cells[i, atCol].Formula = string.Format("=IF(OR({0}=\"{2}\";{1}=\"{2}\");\"{2}\";{0}-{1})", cell1, cell2, string.Empty);
//ws.Cells[i, atCol].Formula = string.Format(@"=IF(OR({0}="";{1}="");"";{0}-{1})", cell1, cell2);
//string formula = string.Format(@"=IF(OR({0}="""";{1}="""");"""";{0}-{1})", cell1, cell2);
//string formula = @"=IF(OR(" + cell1 + "=\"\";" + cell2 + "=\"\");\"\";" + cell1 + "-" + cell2 + ")";
string formula = string.Format("=IF(OR({0}='';{1}='');'';{0}-{1})", cell1, cell2);
ws.Cells[i, atCol].Formula = formula;
}
我正在使用 Win10、VS2015、.Net 4.0 和 EPPLUS 框架进行 excel 操作。
【问题讨论】:
-
为什么不试试单引号呢?
L2='' -
能否请您举一个代码 sn-ps 的示例,尤其是您试图逃避的东西以及它们产生的结果?
-
我试过单引号。结果是:=IF(OR(L2=\'\';M2=\'\');\'\';L2-M2)
-
是的,这个想法并没有逃避他们
-
这并不奇怪,字符串就是这样存储数据的。我相信对框架有更好理解的人可以解释原因。它也不是 string.Format 独有的,如果您使用 stringbuilder 或任何其他方法构建它,就会发生这种情况。无论您使用
\"转义值、使用@""""使其成为文字或使用unicode 值"\u0022\u0022",都会发生这种情况。我要说的是,包括 Interop 在内的所有其他内容都正确处理了转义,就像你说的 WriteLine 一样。我的观点是 EPPLUS 似乎在识别转义序列方面做得不好,但我无法证明这一点。
标签: c# escaping string-formatting epplus double-quotes