Search code examples
.netepplus

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


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.


Solution

  • 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);
    }