ConfusedDeveloper
ConfusedDeveloper

Reputation: 7021

EPPlus: How to add space in a cell value in C#

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?

Upvotes: 4

Views: 6437

Answers (3)

Shahzaib Hassan
Shahzaib Hassan

Reputation: 89

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.

Upvotes: 0

Ernie S
Ernie S

Reputation: 14270

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

Upvotes: 8

snehgin
snehgin

Reputation: 211

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, ' ');

Upvotes: 3

Related Questions