I am creating a spreadsheet from a List<object[]>
using LoadFromArrays
The first entry of the array is a title, the other entries are possibly numbers, text or dates (but the same for each array in the list).
The generated Excel sheet has the green triangle warning that numbers are formatted as text.
I loop through all the cells and set their format to Number like so ws.Cells[i, j].Style.Numberformat.Format = "0";
However the problem remains and I still see the green warning, even though the number format is set to number when I look in the Format Cell...
dialogue.
What are my options here? It is possible for me to know a bit more about what type is in each column, but how do I then set a column title?
Is there a better solution than EPPlus? or some more post processing of the spreadsheet I can do before downloading it?
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<Object[]>
{
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: