[英]Can't create XLSX with apostrophe using ExcelPackage using C#
I am using Excelpackage.codeplex.com
to create xlsx. 我正在使用Excelpackage.codeplex.com
创建xlsx。
When writing a string with apostrophe (') I get a System.Xml.XPath.XPathException
exception. 当用撇号(')编写字符串时,出现System.Xml.XPath.XPathException
异常。
How can I write an xlsx cell with ' using that package? 如何使用该包使用'编写xlsx单元?
private void ExportApostrphoe()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name");
dt.Rows.Add(1, "Ben");
dt.Rows.Add(2, "Joe's");
dt.Rows.Add(3, "Mike");
FileInfo newFile = new FileInfo(@"c:\1.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
OfficeOpenXml.ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("Sheet1");
for (int x = 0; x < dt.Columns.Count; ++x)
{
DataColumn column = dt.Columns[x];
worksheet.Cell(1, 1 + x).Value = column.Caption;
}
for (int x = 0; x < dt.Columns.Count; ++x)
{
for (int y = 0; y < dt.Rows.Count; ++y)
{
worksheet.Cell(2 + y, 1 + x).DataType = "text";
worksheet.Cell(2 + y, 1 + x).Value = Convert.ToString(dt.Rows[y][x]);
}
}
xlPackage.Save();
}
}
Try to update follwoing code in ExcelCell.cs Search for XmlNode stringNode
and update same with below code. 尝试更新ExcelCell.cs中的以下代码搜索XmlNode stringNode
并使用以下代码进行更新。 Create a dll. 创建一个dll。 It worked for me. 它为我工作。
XmlNode stringNode = _xlWorksheet.xlPackage.Workbook.SharedStringsXml.SelectSingleNode(string.Format("//d:si[d:t='{0}']", System.Security.SecurityElement.Escape(Value)), _xlWorksheet.NameSpaceManager);
The Codeplex site for the library has some posts that reference a fix by making changes to the source and recompiling the library, but for a quicker fix I've been able to work around it by replacing single quotes with "right single quotes". 库的Codeplex网站上有一些帖子,它们通过更改源代码并重新编译库来引用修复程序,但是对于更快的修复程序,我可以通过将单引号替换为“正确的单引号”来解决。
So "Bob's" ends up as "Bob′s" - which is totally acceptable for my purposes. 因此,“鲍勃的”最终以“鲍勃的”结尾-对于我的目的,这完全可以接受。
I wrote it as an extension method: 我将其编写为扩展方法:
public static string ReplaceSingleQuote(this string s) {
if (!string.IsNullOrEmpty(s))
return s.Replace('\u0027', '\u2032');
else
return s;
}
so for example you'd change the line: 因此,例如,您需要更改以下行:
worksheet.Cell(2 + y, 1 + x).Value = Convert.ToString(dt.Rows[y][x]);
to : 至 :
worksheet.Cell(2 + y, 1 + x).Value = Convert.ToString(dt.Rows[y][x]).ReplaceSingleQuote();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.