Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# OpenXML将值写入字符串,当转换为数字时,值会发生变化_C#_Excel_Openxml - Fatal编程技术网

C# OpenXML将值写入字符串,当转换为数字时,值会发生变化

C# OpenXML将值写入字符串,当转换为数字时,值会发生变化,c#,excel,openxml,C#,Excel,Openxml,我正在使用OpenXML将一些数据写入Excel。我成功地将所有数据输入到电子表格中,但当我这样做时,所有数据都是字符串格式的。这是因为我主要使用的是上提供的示例代码,它们将数据作为InsertSharedStringItem(Astring)插入Excel。不过,我确实找到了两种方法将单元格转换成数字 第一个是一个简单的CellValues.Number而不是CellValues.SharedString,但这似乎改变了单元格中的所有实际值,并将它们更改为一个数字。举个例子,我在一列中有0,现

我正在使用OpenXML将一些数据写入Excel。我成功地将所有数据输入到电子表格中,但当我这样做时,所有数据都是字符串格式的。这是因为我主要使用的是上提供的示例代码,它们将数据作为
InsertSharedStringItem
(A
string
)插入Excel。不过,我确实找到了两种方法将单元格转换成数字

第一个是一个简单的
CellValues.Number
而不是
CellValues.SharedString
,但这似乎改变了单元格中的所有实际值,并将它们更改为一个数字。举个例子,我在一列中有0,现在是5,11是0,21是33,诸如此类的奇怪的东西(如果数字像0一样重复,它们都会变为5,在0的情况下是5)。显然这行不通

然后,我在Excel中找到了另一种将字符串转换为数字的方法,并找到了它(如果您单击该答案中的链接以转到该用户源,则需要将“www.”添加到URL)。这个解决方案的问题是,它会将所有字符串转换为双精度字符串,但这些值与第一个解决方案的变化相同,只是这次采用了双精度格式

还值得注意的是,我的第三列应该是一个字符串,不需要转换为数字,但它无论如何都可以

这就是我正在处理的问题:

private static void WriteToExcel(string[] contents, char[] desiredColumns)
{
    string filePath = @"D:\Folder\test.xlsx";
    try
    {
        using (SpreadsheetDocument StatsCollection = SpreadsheetDocument.Open(filePath, true))
        {
            string sheetName = "";
            int totalRows = contents.Length / 15;
            int contentsIndex = 0;
            for (uint indexRow = 1; indexRow < totalRows; indexRow++)
            {
                for (int indexCol = 1; indexCol < 16; indexCol++)
                {
                    sheetName = "Sheet1";
                    SharedStringTablePart shareStringPart;
                    if (StatsCollection.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
                    {
                        shareStringPart = StatsCollection.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                    }
                    else
                    {
                        shareStringPart = StatsCollection.WorkbookPart.AddNewPart<SharedStringTablePart>();
                    }
                    int index = InsertSharedStringItem(contents[contentsIndex], shareStringPart);
                    WorkbookPart bookPart = StatsCollection.WorkbookPart;
                    Sheet mySheet = bookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();
                    WorksheetPart sheetPart = (WorksheetPart)(bookPart.GetPartById(mySheet.Id));
                    Cell cell = InsertCellInWorksheet(desiredColumns[indexCol - 1].ToString(), indexRow, sheetPart);
                    cell.CellValue = new CellValue(index.ToString());

                    //I added the following if structure to check for numbers
                    if (IsNumeric(contents[contentsIndex].ToString()))
                    {
                        cell.DataType = new EnumValue<CellValues>(CellValues.Number);
                    }
                    else
                    {
                        cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
                    }

                    /*I removed the following lines                            
                    Stylesheet styleSheet = bookPart.WorkbookStylesPart.Stylesheet;
                    uint _doubleStyleId = createCellFormat(styleSheet, null, null, UInt32Value.FromUInt32(4));
                    cell.StyleIndex = _doubleStyleId;
                    */
                    sheetPart.Worksheet.Save();
                    contentsIndex++;
                }
            }
            Console.WriteLine("Copy Complete.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Cannot find output Excel file.\n" + ex.Message);
    }
}
当我尝试将单元格值从字符串转换为数字时,它会按预期进行转换,但会更改值。为什么会发生这种情况,我如何解决这个问题,以及如何防止我的一列实际字符串被更改为一个数字

更新:

我通过以下解决方案修复了字符串到数字的转换,并相应地更新了代码,添加了以下方法

private static bool IsNumeric(string value)
{
    double output = 0;
    if(Double.TryParse(value, out output))
    {
        return true;
    }
    else
    {
        return false;
    }
}

现在所有应该是数字的东西都是数字,所有需要保持字符串的东西都是字符串。然而,我的数字的实际值仍在更改中(应该是0的数字是5,11是0,21是33,等等)。

问题在于
CellValue
只是作为字符串的索引。您应该使用实际数组
contents[contentsindex]
进行数字运算,因为您希望显示该数组的内容,而不是
索引的值。将
CellValue
部分添加到if..else。。。声明如下所示@蓝巴伦和我在聊天中一起解决了这个问题

if (IsNumeric(contents[contentsIndex]))
{
    cell.DataType = new EnumValue<CellValues>(CellValues.Number);
    cell.CellValue = new CellValue(contents[contentsIndex]);
}
else
{
    cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
    cell.CellValue = new CellValue(index.ToString());
}
if(IsNumeric(contents[contentsIndex]))
{
cell.DataType=新的枚举值(CellValues.Number);
cell.CellValue=新的CellValue(内容[contentsIndex]);
}
其他的
{
cell.DataType=新的枚举值(CellValues.SharedString);
cell.CellValue=新的CellValue(index.ToString());
}

我希望链接到MSDN就足够了,但我也可以发布这两种方法。不,我错过了,让我看看。
if (IsNumeric(contents[contentsIndex]))
{
    cell.DataType = new EnumValue<CellValues>(CellValues.Number);
    cell.CellValue = new CellValue(contents[contentsIndex]);
}
else
{
    cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
    cell.CellValue = new CellValue(index.ToString());
}