如何使用C#将文本值转换为Excel 2003中的数字值(存储为文本的数字)

时间:2010-01-27 12:28:13

标签: c# vsto excel-2003

似乎有很多建议可以做到这一点,其中没有任何建议可行。

实际上,我想要将Excel工作表中的文本值更改为数字(这是一个已设置为存储为文本的数字的单元格,旁边有一个绿色菱形)。

这个webpage详细说明了如何通过用户界面解决Excel中的问题,我将其记录为下面的宏(但这是VBA)......

包括将值设置为自身:

                Range allCellsRng;
                string lowerRightCell = "AZ500";
                allCellsRng = wSheet.get_Range("A1", lowerRightCell).Cells;
                foreach (Range cell in allCellsRng)
                {
                    if (cell.Value2.ToString().Length > 0)
                    {
                        cell.Value2 = cell.Value2;
                    }
                }

这是一个记录的VB宏,显示了解决问题的方法,但我在C#中遇到问题时出现了问题:

ActiveCell.FormulaR1C1 = "0"
Range("A1").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks _
    :=False, Transpose:=False
Range("A1").Select

3 个答案:

答案 0 :(得分:1)

使用Clear Office,代码非常简单:

SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName);
foreach (Worksheet worksheet in spreadsheetDocument.Workbook.Sheets.OfType<Worksheet>())
{
    foreach (Cell cell in worksheet.GetRange("A1:AZ500"))
    {
        string s = cell.Value as string;
        if (s == null)
            continue;
        double d;
        if (double.TryParse(s, out d))
            cell.Value = d;
        }
    }
spreadsheetDocument.Save();

答案 1 :(得分:0)

更改单元格的格式不是更好吗?我相信你应该能够使用

获取格式
range.NumberFormat

并将其更改为您想要的实际格式...然后您可以设置整个列或整个工作表的范围。

答案 2 :(得分:0)

好的,所以在这里提出一个问题引发了脑电波。这似乎有效:

Range cellA1 = wSheet.get_Range("A1", System.Type.Missing);
cellA1.Value2 = "0";
cellA1.Copy(System.Type.Missing);
Range cellAll = wSheet.get_Range("A1:AZ500", System.Type.Missing);
cellAll.PasteSpecial(XlPasteType.xlPasteAll, XlPasteSpecialOperation.xlPasteSpecialOperationAdd,
        false, false);