4

I am currently working in an export to Excel of a hierarchical grid using EPPlus. So all child rows should be displayed with padding (space). As shown below:

Enter image description here

As shown in the above, you can see I have added four spaces before Software, QA, Analyst, etc.

I have used the below code to add space:

worksheet.cells[1, 1].value = "    Software";

But this doesn't seem to be the proper way to me. I have tried with \t, but that doesn't work.

Is there a better approach I can use here?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ConfusedDeveloper
  • 6,389
  • 4
  • 21
  • 36

3 Answers3

8

Use Style.Indent like this:

ws.Cells["A4"].Style.Indent = 5;

Here is a reference for how it is done inside the actual Excel UI:

How to indent cell data in Excel 2010

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ernie S
  • 13,902
  • 4
  • 52
  • 79
3

Another way would be to use an Excel formula to pad left, like:

string str = "SampleString";
objWorksheet.Cells[3, 1].Formula = string.Format("=REPT(\" \",1)&\"{0}\"", str);

Or pad the string directly like

string str = "SampleString";
objWorksheet.Cells[2, 1].Value = str.PadLeft(str.Length + 1, ' ');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
snehgin
  • 191
  • 1
  • 1
  • 8
0

If you just want padding on the left and right side, you can also do this dynamically like this:

foreach (var cell in worksheet.Cells[1, 1, 1, 1])
{
    cell.Value = $"   {cell.Value}   ";
}

Just change the range.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131