Using EPPlus how can I generate a spreadsheet where numbers are numbers not text

前端 未结 3 878
醉话见心
醉话见心 2020-12-10 13:39

I am creating a spreadsheet from a List using LoadFromArrays

The first entry of the array is a title, the other entries are

3条回答
  •  無奈伤痛
    2020-12-10 14:31

    Since you are using objects arrays they can contain numbers and strings that look like numbers you will have to go through each object and determine its type:

    [TestMethod]
    public void Object_Type_Write_Test()
    {
        //http://stackoverflow.com/questions/31537981/using-epplus-how-can-i-generate-a-spreadsheet-where-numbers-are-numbers-not-text
        var existingFile = new FileInfo(@"c:\temp\temp.xlsx");
        if (existingFile.Exists)
            existingFile.Delete();
    
        //Some data
        var list = new List
        {
            new object[]
            {
                "111.11",
                111.11,
                DateTime.Now
            }
        };
    
        using (var package = new ExcelPackage(existingFile))
        {
            var ws = package.Workbook.Worksheets.Add("Sheet1");
            ws.Cells[1, 1, 2, 2].Style.Numberformat.Format = "0";
            ws.Cells[1, 3, 2, 3].Style.Numberformat.Format = "[$-F400]h:mm:ss\\ AM/PM";
    
            //This will cause numbers in string to be stored as string in excel regardless of cell format
            ws.Cells["A1"].LoadFromArrays(list);
    
            //Have to go through the objects to deal with numbers as strings
            for (var i = 0; i < list.Count; i++)
            {
                for (var j = 0; j < list[i].Count(); j++)
                {
    
                    if (list[i][j] is string)
                        ws.Cells[i + 2, j + 1].Value = Double.Parse((string) list[i][j]);
                    else if (list[i][j] is double)
                        ws.Cells[i + 2, j + 1].Value = (double)list[i][j];
                    else
                        ws.Cells[i + 2, j + 1].Value = list[i][j];
    
                }
            }
    
            package.Save();
        }
    }
    

    With the above, you see the image below as the output Note the upper left corner cell with the green arrow because it was a string that was written by LoadFromArray which looks like a number:

    Excel Output

提交回复
热议问题