Hello,
I have following issue:
When loading data to an excel worksheet, it is required to format the datetime value to following format: "dd/MM/yyyy". But when I apply some custom style in code, the style isn't applied in the worksheet. It is shown as a number.
I have used following code to reproduce the bug:
var workbook = new Workbook();
workbook.Worksheets.Add(SheetType.Worksheet);
workbook.Worksheets[0].Cells.Columns[0].Style.Custom = "dd/MM/yyyy";
workbook.Worksheets[0].Cells[0,0].PutValue(DateTime.Today);
using(FileStream stream = new FileStream(@"C:\Temp\fileWithDateTime.xlsx",FileMode.OpenOrCreate))
{
workbook.Save(stream,SaveFormat.Xlsx);
}
This solution worked for Aspose.Cells version 4.3 (format applied correctly),
but when upgrading to Aspose.Cells version 7.0 and 7.2,
the bug was introduced.
Is it possible to fix this, or suggest a proper workaround ?
Thanks in advance,
Kevin Aelbrecht
Hi,
Thanks for your posting and using Aspose.Cells for .NET.
Please download and use the latest version:
Aspose.Cells
for .NET v7.2.0.4
Please see the following code, how to apply your custom style. Please use the Cell.GetStyle() and Cell.SetStyle() methods to apply your custom style.
Please also see the output file generated by this code and the screenshot below. The code puts a date value inside cell A1 and then apply your custom style.
C#
var workbook =
new Workbook();
workbook.Worksheets.Add(SheetType.Worksheet);
Worksheet worksheet = workbook.Worksheets[0];
Cell cell = worksheet.Cells[“A1”];
Style style = cell.GetStyle();
style.Custom = “dd/MM/yyyy”;
cell.SetStyle(style);
cell.PutValue(DateTime.Today);
worksheet.AutoFitColumns();
workbook.Save(“output.xlsx”);
Screenshot:
Hi,
It is not an issue by any means rather in latest versions, the Cell/Column/Row.Style property is read-only and you cannot apply style using it. For applying style to Column or Row, you need to create a Style object and specify your desired formatting with style flag on, now apply style to the column or row for your needs.
See the updated code, it works absolutely fine.
Sample code:
var workbook = new Workbook();
int i = workbook.Worksheets.Add(SheetType.Worksheet);
Style style = workbook.CreateStyle();
style.Custom = “dd/MM/yyyy”;
StyleFlag flag = new StyleFlag();
flag.NumberFormat = true;
workbook.Worksheets[0].Cells.Columns[0].ApplyStyle(style,flag);
workbook.Worksheets[0].Cells[0, 0].PutValue(DateTime.Today);
using (FileStream stream = new FileStream(@“e:\test2\fileWithDateTime.xlsx”, FileMode.OpenOrCreate))
{
workbook.Save(stream, SaveFormat.Xlsx);
}
For complete reference, see the document:
Thank you.
Thanks a lot for the quick response to this issue.
I didn't know the property was set to read-only,
so by simple applying a new style,
the format is done correctly.
Thanks a lot !!
Kevin