Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel interop - how to stop number (stored as text) being "evaluated"

I was wondering if anyone had come across the following problem and had any ideas on how to resolve it: I'm exporting data from a C# application (.NET 3.5) to Excel (2003) via Interop. One of the columns stores a string value that appears to be numeric. That is to say it is a number that begins with a 0 e.g. 000123

I need the full number to be stored as it may be a serial number or something similar. Excel is not keen on this so I thought I could get around it by setting the destination cell to general. When I export to Excel I find 123 stored instead of 000123.

I've run through the app in debug and from the watchlist I've found that (for "Range range":

range.NumberFormat = "General"`
this.Rows[iGridRow].Cells[iGridCol].Value = "000123" '/* (datagrid is not truncating it)*/
range.Value2 = 123.0

It seems to be getting handled as a number even though I set the numberformat before this point:

range.NumberFormat = sNumberFormat;
range = (Range)sheet.Cells[iExcelRow, iExcelCol];
range.Value2 = this.Rows[iGridRow].Cells[iGridCol].Value.ToString();

Can anyone please help?

like image 364
Daniel Snowden Avatar asked Jun 28 '10 11:06

Daniel Snowden


2 Answers

Add a single apostrophe ' before the number. Excel will then treat the number as a string.

like image 80
Binary Worrier Avatar answered Sep 29 '22 00:09

Binary Worrier


I know it's late, but maybe someone need this in the future. It's not really for the performance but you can store it in a two-dimentional array first.

object[,] Values = new object[iGrid.Rows.Count, IGrid.Columns.Count];
            for (int i = 0; i < alllogentry.Rows.Count; i++)
            {
                for (int j = 0; j < alllogentry.Columns.Count; j++)
                {
                    if (alllogentry.Rows[i].Cells[j].Value != null)
                    {
                        Values[i, j] = alllogentry.Rows[i].Cells[j].Value.ToString();
                    }
                    else
                    {
                        Values[i, j] = " ";
                    }
                }
            }

This way number stays number and string stays string.

Also pass the information via bulk insert to excel not cell by cell. That was my code.

// Bulk Transfer
String MaxRow = (alllogentry.Rows.Count+6).ToString();
 String MaxColumn = ((String)(Convert.ToChar(alllogentry.Columns.Count / 26 + 64).ToString() + Convert.ToChar(alllogentry.Columns.Count % 26 + 64))).Replace('@', ' ').Trim();
String MaxCell = MaxColumn + MaxRow;

//Format
worksheet.get_Range("A1", MaxColumn + "1").Font.Bold = true;
worksheet.get_Range("A1", MaxColumn + "1").VerticalAlignment = XlVAlign.xlVAlignCenter;

// Insert Statement
    worksheet.get_Range("A7", MaxCell).Value2 = Values;
like image 23
Matthias Avatar answered Sep 29 '22 01:09

Matthias