Excel互操作 – 如何停止数字(存储为文本)被“评估”

我想知道是否有人遇到以下问题,并有如何解决它的任何想法:我正在通过Interop从C#应用程序(.NET 3.5)导出到Excel(2003)的数据。 其中一列存储显示为数字的string值。 也就是说这是一个以0,例如000123开头的数字

我需要存储完整的号码,因为它可能是一个序列号或类似的东西。 Excel不喜欢这个,所以我想我可以通过设置目标单元格来解决这个问题。 当我导出到Excel时,我发现存储123而不是000123。

我已经通过debugging中的应用程序运行,并从我发现的监视列表(对于“Range range”:

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

它似乎被作为一个数字处理,即使我在此之前设置数字格式:

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

任何人都可以请帮忙?

在数字前添加一个单引号。 Excel然后将数字视为一个string。

我知道这很晚了,但是也许有人在将来需要这个。 这不是真正的性能,但可以将它存储在一个二维数组中。

 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] = " "; } } } 

这种方式编号保持数字和string保持string。

也通过批量插入传递的信息不擅长细胞。 那是我的代码。

 // 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; 

我使用这个macros。 它在每个单元格中的每个数值之前插入一个撇号。

 Sub Macro1() Dim rwIndex As Integer Dim colIndex As Integer For rwIndex = 1 To ActiveSheet.UsedRange.Rows.Count For colIndex = 1 To ActiveSheet.UsedRange.Columns.Count If IsNumeric(Cells(rwIndex, colIndex).Value) Then _ Cells(rwIndex, colIndex).Value = "'" _ & Cells(rwIndex, colIndex).Value Next colIndex Next rwIndex End Sub 

正确的types不是一般的,因为一般会尝试猜测正确的types,在这种情况下是一个数字,但你必须指定它为文本不截断前导零。

试试下面的代码:

 Range cell = ActiveWorksheet.Cells[1,1]; //The @ is the indicator for Excel, that the content should be text const string textIndicator = "@"; //Change the NumberFormat from 'General' to 'Text' cell.NumberFormat = textIndicator; //Set the Value cell.Value2 = "000123";