Search code examples
c#excelinteropoffice-interop

Removing a blank character in-front of a value in a cell C#


I'm currently busy with a application that manipulates excel data using C#. I have encountered a problem however.

The data in the column all has a blank space in-front of it, which messes up with the Sum() functionality.

I've got this method to read each row from the column and remove the blank space in-front of the data.

private void BlankCheck()
        {
            string Val,NT;
            int RCount = xlWorksheet.UsedRange.Rows.Count;
            for(int X = 3; X < RCount; X++)
            {
                Val = (string)(xlWorksheet.Cells[X, 8] as Excel.Range).Text;
                NT = Val.Trim();
                xlWorksheet.Cells[X, 8] = "\b"+NT.ToString();
            }
            xlApp.Quit();
            ReleaseObject(xlWorksheet);
            ReleaseObject(xlWorkbook);
            ReleaseObject(xlApp);
        }

The results produced by this are correct as shown by the screenshot below Results of the method

Now this is where the problem is, when opening up the new excel document, the blank spaces are all still in-front of the data. So I've added the "\b" to the string when it writes to the cell, however this is the result.

Excel sheet result

I'm not sure why those [] have appeared ? Any suggestions ?

Edited Data

This is what the excel column looks like both before and after the code has run without the /b. Not sure if you can see it, but there is a blank character in-front of the times. Here is the code too for those who have asked.

private void BlankCheck()
        {
            string Val,NT;
            int RCount = xlWorksheet.UsedRange.Rows.Count;
            for(int X = 3; X < RCount; X++)
            {
                Val = (string)(xlWorksheet.Cells[X, 8] as Excel.Range).Text;
                NT = Val.Trim();
                xlWorksheet.Cells[X, 8] = NT.ToString();
            }
            xlApp.Quit();
            ReleaseObject(xlWorksheet);
            ReleaseObject(xlWorkbook);
            ReleaseObject(xlApp);
        }

Thanks


Solution

  • I think it would help, if you called xlWorkbook.Save() before releasing the object.