Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/MiniExcel.OpenXml/Templates/OpenXmlTemplate.Images.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private sealed class ImageStateScope(OpenXmlTemplate template) : IDisposable
}

private string GetFormattedValueWithImages(PropertyInfo? propInfo, object? cellValue, Type? type)
=> GetImageMarker(cellValue) ?? GetFormattedValue(propInfo, cellValue, type);
=> GetImageMarker(cellValue) ?? GetFormattedValue(propInfo, cellValue, type, _configuration.Culture);

/// <summary>
/// Walks the remaining segments of a dotted placeholder expression from an already resolved root
Expand Down
20 changes: 12 additions & 8 deletions src/MiniExcel.OpenXml/Templates/OpenXmlTemplate.Impl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,7 @@ private async Task<GenerateCellValuesContext> GenerateCellValuesAsync(
/// Formats the given cell value into a string representation suitable for OpenXml injection.
/// Handles specific types like booleans, dates, enums, and numeric values.
/// </summary>
private static string GetFormattedValue(PropertyInfo? propInfo, object? cellValue, Type? type)
private static string GetFormattedValue(PropertyInfo? propInfo, object? cellValue, Type? type, CultureInfo culture)
{
string? cellValueStr;
if (type == typeof(bool))
Expand All @@ -829,7 +829,7 @@ private static string GetFormattedValue(PropertyInfo? propInfo, object? cellValu
}
else if (type == typeof(DateTime))
{
cellValueStr = ConvertToDateTimeString(propInfo, cellValue);
cellValueStr = ConvertToDateTimeString(propInfo, cellValue, culture);
}
else if (type?.IsEnum is true)
{
Expand Down Expand Up @@ -1020,14 +1020,14 @@ private void ProcessFormulas(StringBuilder rowXml, int rowIndex)
rowXml.Append(rowElement.FirstNode);
}

private static string? ConvertToDateTimeString(PropertyInfo? propInfo, object? cellValue)
private static string? ConvertToDateTimeString(PropertyInfo? propInfo, object? cellValue, CultureInfo culture)
{
//TODO:c.SetAttribute("t", "d"); and custom format
var format = propInfo?.GetAttributeValue((MiniExcelFormatAttribute x) => x.Format)
?? propInfo?.GetAttributeValue((MiniExcelColumnAttribute x) => x.Format)
?? "yyyy-MM-dd HH:mm:ss";

return (cellValue as DateTime?)?.ToString(format);
return (cellValue as DateTime?)?.ToString(format, culture);
}

//TODO: need to optimize
Expand Down Expand Up @@ -1423,9 +1423,13 @@ private void UpdateDimensionAndGetRowsInfo(IDictionary<string, object?> inputMap
// Convert to string using invariant culture: if the current culture were to be set to de-DE or tr-TR
// a value such as the date "01.01.2021" would read as the number 1012021 once converted back to decimal,
// for "." is utilized as the group separator.
var cellValueStr = resolvedValue is IFormattable formattable && TypeHelper.IsNumericType(resolvedValue.GetType())
? formattable.ToString(null, CultureInfo.InvariantCulture)
: resolvedValue?.ToString();
// Dates are formatted here rather than only in the DateTime branch below, so that a date inside other
// text ("Created: {{CreateDate}}") also uses the configured culture, as in the IEnumerable rows.
var cellValueStr = resolvedValue is DateTime dateValue
? dateValue.ToString("yyyy-MM-dd HH:mm:ss", _configuration.Culture)
: resolvedValue is IFormattable formattable && TypeHelper.IsNumericType(resolvedValue.GetType())
? formattable.ToString(null, CultureInfo.InvariantCulture)
: resolvedValue?.ToString();

// No exponent: "1E-30" would underflow decimal to 0, so such values keep their text as before.
const NumberStyles allowedNumberStyles =
Expand All @@ -1448,7 +1452,7 @@ private void UpdateDimensionAndGetRowsInfo(IDictionary<string, object?> inputMap
else if (resolvedValue is DateTime timestamp)
{
//c.SetAttribute("t", "d");
cellValueStr = timestamp.ToString("yyyy-MM-dd HH:mm:ss");
cellValueStr = timestamp.ToString("yyyy-MM-dd HH:mm:ss", _configuration.Culture);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

if (string.IsNullOrEmpty(cellValueStr) && string.IsNullOrEmpty(cell.Attribute("t")?.Value))
Expand Down
50 changes: 50 additions & 0 deletions tests/MiniExcel.OpenXml.Tests/Templates/MiniExcelTemplateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,56 @@ public void TemplateValuesDoNotDependOnCurrentCulture()
Assert.NotEqual(0d, Convert.ToDouble(tinyPoints, CultureInfo.InvariantCulture));
}

[Fact]
public void TemplateDatesIgnoreCurrentCulture()
{
var culture = CultureInfo.CurrentCulture;
try
{
// th-TH formats dates with the Buddhist calendar (2021 is 2564) and fi-FI separates hours with "."
foreach (var name in new[] { "th-TH", "fi-FI" })
{
CultureInfo.CurrentCulture = new CultureInfo(name);

using var scalarPath = AutoDeletingPath.Create();
_excelTemplater.FillTemplate(scalarPath.ToString(), PathHelper.GetFile("xlsx/TestTemplateEasyFill.xlsx"), new
{
Name = "Jack",
CreateDate = new DateTime(2021, 01, 01, 13, 45, 0),
VIP = true,
Points = 123
});
var scalarRows = _excelImporter.Query(scalarPath.ToString()).ToList();
Assert.Equal("2021-01-01 13:45:00", scalarRows[1].B);

// A date inside other text skips the DateTime branch of the scalar path
using var mixedTemplatePath = AutoDeletingPath.Create();
MiniExcelV2.Exporters.GetOpenXmlExporter().Export(mixedTemplatePath.ToString(), new[]
{
new Dictionary<string, object> { ["Label"] = "Created: {{CreateDate}}" }
});
using var mixedPath = AutoDeletingPath.Create();
_excelTemplater.FillTemplate(mixedPath.ToString(), mixedTemplatePath.ToString(), new { CreateDate = new DateTime(2021, 01, 01, 13, 45, 0) });
var mixedRows = _excelImporter.Query(mixedPath.ToString()).ToList();
Assert.Equal("Created: 2021-01-01 13:45:00", mixedRows[1].A);

using var listPath = AutoDeletingPath.Create();
_excelTemplater.FillTemplate(listPath.ToString(), PathHelper.GetFile("xlsx/TestTemplateGithubProjects.xlsx"), new
{
User = "ITWeiHan",
Projects = new[] { new { Name = "MiniExcel", Link = "https://github.com/mini-software/MiniExcel", Star = 146, CreateTime = new DateTime(2021, 03, 01, 13, 45, 0) } },
TotalStar = 146
});
var listRows = _excelImporter.Query(listPath.ToString()).ToList();
Assert.Contains(listRows, row => ((IDictionary<string, object>)row).Values.Contains("2021-03-01 13:45:00"));
}
}
finally
{
CultureInfo.CurrentCulture = culture;
}
}

[Fact]
public void TemplateBasicTest()
{
Expand Down
Loading