How to load text containing commas in a single Excel cell with EPPlus

房东的猫 提交于 2020-06-27 10:12:24

问题


I'm giving a try to the EPPlus library and I'm stucked at this: I have to load a text in a single cell, but when this text contains a comma the code that I'm using split my text along multiple cells (along the right direction). Here is the code that I'm using to load the text:

using (ExcelPackage pck = new ExcelPackage())
{
   //Create the worksheet
   ExcelWorksheet ws = pck.Workbook.Worksheets.Add("MySheet");
   using (ExcelRange range = ws.Cells[1, 1])
   {
      range.LoadFromText("this works");
   }
   using (ExcelRange range = ws.Cells[1, 2])
   {
      range.LoadFromText("this, splits my , text in 3 parts");
   }
}

I don't find a way to operate on a single cell or to instruct the LoadFromText method to not split my text.


回答1:


You could wrap it in double quotes by specifying the TextQualifier

using (ExcelRange range = ws.Cells[1, 1])
{
   var format = new OfficeOpenXml.ExcelTextFormat();
   format.Delimiter = ',';
   format.TextQualifier = '"';
   format.DataTypes = new[] { eDataTypes.String };
   range.LoadFromText("this, should, work, also, now", format);
}



回答2:


You can actually reference a single cell and set its value and avoid to modify the Delimiter.

using (ExcelRange range = ws.Cells[1, 1])
{
    range.First().Value = "this, should, work";
}

The above assumes that the referenced cell is already created. If it has not already been set to a value, it will give an Object reference not set to an instance of an object error. So, to avoid this you can set a dummy value right before, just to create the cell.

using (ExcelRange range = ws.Cells[1, 1])
{
    range.LoadFromText("-"); // This will create the cell
    range.First().Value = "this, should, work";
}


来源:https://stackoverflow.com/questions/16356959/how-to-load-text-containing-commas-in-a-single-excel-cell-with-epplus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!