c#open xml将现有单元格重新格式化为数字

问题描述 投票:0回答:1

我有一个现有的电子表格。我想将一些细胞从generalcustom重新格式化为Number。但由于某些原因,当我将它们重新格式化为数字时,单元格值会变为某个随机数。

这是我的代码的样子

           using (var d = SpreadsheetDocument.Open(_docPath, true))
            {
                var workSheet = GetWorksheetPart(d.WorkbookPart.Workbook.WorkbookPart, "Project Summary");

                foreach (var cellRef in _ProjectRequirementsFormService.NumberCellReferences)
                {
                    Cell theCell = workSheet.Worksheet.Descendants<Cell>().Where(c => c.CellReference == cellRef).FirstOrDefault();
                    if (theCell != null) {
                        //For some reason This line of code replaces the cell value with a value 5197
                        //and every iteration of the loop increments the value of the next cell found 5198, 5199, etc....
                        theCell.DataType = CellValues.Number;
                    }
                }
...
}

    public WorksheetPart GetWorksheetPart(WorkbookPart workbookPart, string sheetName)
    {
        string relId = workbookPart.Workbook.Descendants<Sheet>().First(s => sheetName.Equals(s.Name)).Id;
        return (WorksheetPart)workbookPart.GetPartById(relId);
    }

现在由于某种原因,这行代码theCell.DataType = CellValues.Number;用值5197替换单元格值,并且循环的每次迭代都会增加找到的下一个单元格的值5198,5199等....

当我评论有缺陷的线时,我在单元格中得到正确的值,但格式不是Number

enter image description here

这是我添加代码行以将其更改为数字格式时的样子。为什么它会更改所有单元格值以及如何修复它?

enter image description here

链接到示例文件

https://drive.google.com/file/d/0B7UImeY4gR3VdnBBZmdWSHJqN2lhRmFqY1N6THJXNmIzZDhF/view?usp=sharing

c# openxml-sdk
1个回答
1
投票

使用Microsoft Open XML SDK工具将xlsx反编译为C#。

https://www.microsoft.com/en-us/download/details.aspx?id=30425

您将看到您的单元格具有SharedString数据类型。它是一种id,单元格存储id,而值存储在sharedstring表中。您在更改datetype后看到的这些奇怪数字是sharedstring表中的这些ID。更改DataType并不会真正改变值的存储方式,而是会更改它们的解释方式。如果将其类型更改为数字,它们仍将是“以字符串形式存储的数字”。例如,让我们看看单元格“E17”:

Cell cell261 = new Cell(){ CellReference = "E17", StyleIndex = (UInt32Value)11U, DataType = CellValues.SharedString };
CellValue cellValue90 = new CellValue();
cellValue90.Text = "26";

......应该是50000不是吗?

        SharedStringItem sharedStringItem27 = new SharedStringItem();
        Text text45 = new Text();
        text45.Text = "50000";
        sharedStringItem27.Append(text45);

要从电子表格中读取正确的值,您需要使用ms docs示例中的GetCellValue代码。

https://docs.microsoft.com/en-us/office/open-xml/how-to-retrieve-the-values-of-cells-in-a-spreadsheet

然后你可以写下面的代码来读取真实的单元格值(我改了一下并传递文档而不是文件路径)解析它并保存为十进制类型:

var value = GetCellValue(d, "Sheet1", cellRef.CellReference);

if (!string.IsNullOrEmpty(value))
{
  if (decimal.TryParse(value, out decimal val))
   {
      cellRef.CellValue = new 
      CellValue(DocumentFormat.OpenXml.DecimalValue.FromDecimal(val));
      cellRef.StyleIndex = 0U;                            
   }
 }

StyleIndex 0U似乎是通用格式,但由于您具有正确的单元格类型,因此无关紧要。即使我仍然没有得到原因=当你打开固定的xlsx时,不计算总和公式。

© www.soinside.com 2019 - 2024. All rights reserved.