簡體   English   中英

Excel互操作 - 如何停止“評估”的數字(存儲為文本)

[英]Excel interop - how to stop number (stored as text) being “evaluated”

我想知道是否有人遇到以下問題,並對如何解決它有任何想法:我通過Interop將數據從C#應用程序(.NET 3.5)導出到Excel(2003)。 其中一列存儲了一個看似數字的字符串值。 也就是說它是一個以0開頭的數字,例如000123

我需要存儲完整的號碼,因為它可能是序列號或類似的東西。 Excel並不熱衷於此,所以我認為我可以通過將目標單元格設置為常規來繞過它。 當我導出到Excel時,我發現123存儲而不是000123。

我在調試中運行了應用程序,並從我發現的監視列表(對於“范圍范圍”:

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會將該數字視為字符串。

我知道現在已經很晚了,但也許有人在將來需要這個。 它不是真正的性能,但你可以先將它存儲在一個二維數組中。

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

這樣,數字保持數字,字符串保持字符串。

同時通過批量插入將信息傳遞給excel而不是逐個單元格。 那是我的代碼。

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

我用這個宏。 它在每個單元格中的數值之前插入一個撇號。

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

正確的類型不是常規類型,因為一般會嘗試猜測正確的類型,在這種情況下是數字,但您必須將其指定為文本以不截斷前導零。

請嘗試以下代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM