[英]Excel date format using EPPlus
我在將單元格格式化為 Date 時遇到問題。
FileInfo info = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(info))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add(sheetName);
ws.Cells[3, 1].Style.Numberformat.Format = "yyyy-mm-dd";
ws.Cells["A3"].Formula = "=DATE(2014,10,5)";
}
Excel 中的輸出:41 917,00
為什么這不起作用?
我同意 Yosoyke。 您可能瞄准了錯誤的細胞。 你可以試試:
ws.Cells["A3"].Style.Numberformat.Format = "yyyy-mm-dd";
ws.Cells["A3"].Formula = "=DATE(2014,10,5)";
worksheet.Cells["YOURDATECELL_OR_YOURDATECELLRANGE"].Style.Numberformat.Format = "mm-dd-yy";
如果您使用 taraz 提到的公式。 最后添加 worksheet.Calculate() 。 參考https://epplus.codeplex.com/wikipage?title=About%20Formula%20calculation
或者不使用公式,替代方法
private static decimal GetExcelDecimalValueForDate(DateTime date)
{
DateTime start = new DateTime(1900, 1, 1);
TimeSpan diff = date - start;
return diff.Days + 2;
}
worksheet.Cells["A2"].Value = GetExcelDecimalValueForDate(Convert.ToDateTime('2016-04-29'));
worksheet.Cells["A2"].Style.Numberformat.Format = "mm-dd-yy";//or m/d/yy h:mm
默認情況下,當 excel 保存日期字段時,它將其保存為numFormatId
14(查看 xls 中的 xml 文件)。 這可確保在打開文件時在任何國家/地區正確設置日期格式。 在 Epplus 中mm-dd-yy
轉換為numFormatId
14 for excel。 這將確保當文件在任何國家/地區打開時,日期將根據該國家/地區的短日期設置正確格式化。 還注意到m/d/yy h:mm
格式對於任何國家都是正確的。
var dateColumns = from DataColumn d in dt.Columns
where d.DataType == typeof(DateTime) || d.ColumnName.Contains("Date")
select d.Ordinal + 1;
foreach (var dc in dateColumns)
{
worksheet.Cells[2, dc, rowCount + 2, dc].Style.Numberformat.Format = "mm/dd/yyyy hh:mm:ss AM/PM";
}
它將所有帶有標題日期的列格式化為給定/提供的特定格式
我在轉換 CSV 時遇到了同樣的問題。 我能夠以稍微不同的方式做到這一點。
private string ConvertToExcel(string CSVpath, string EXCELPath)
{
try
{
string Filename = System.IO.Path.GetFileNameWithoutExtension(CSVpath);
string DirectoryName = System.IO.Path.GetDirectoryName(CSVpath);
EXCELPath = DirectoryName + "\\" + Filename + ".xlsx";
string worksheetsName = "Report";
bool firstRowIsHeader = false;
var format = new OfficeOpenXml.ExcelTextFormat();
format.Delimiter = '|';
format.EOL = "\n";
using (OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(new System.IO.FileInfo(EXCELPath)))
{
string dateformat = "m/d/yy h:mm";
//string dateformat = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
OfficeOpenXml.ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(new System.IO.FileInfo(CSVpath), format, OfficeOpenXml.Table.TableStyles.Medium2, firstRowIsHeader);
worksheet.Column(3).Style.Numberformat.Format = dateformat;
worksheet.Column(5).Style.Numberformat.Format = dateformat;
worksheet.Column(6).Style.Numberformat.Format = dateformat;
worksheet.Column(20).Style.Numberformat.Format = dateformat;
worksheet.Column(21).Style.Numberformat.Format = dateformat;
worksheet.Column(22).Style.Numberformat.Format = dateformat;
package.Save();
}
}
catch (Exception ex)
{
//DAL.Operations.Logger.LogError(ex);
Console.WriteLine(ex);
Console.Read();
}
return EXCELPath;
}
通用解決方案采用 IEnumerable(數據),它遍歷通用對象的屬性,找到 DateType 或 nullableDate 類型並應用格式:
//set the list of dateColumns which will be used to formate them
List<int> dateColumns = new List<int>();
//get the first indexer
int datecolumn = 1;
//loop through the object and get the list of datecolumns
foreach (var PropertyInfo in data.FirstOrDefault().GetType().GetProperties())
{
//check if property is of DateTime type or nullable DateTime type
if (PropertyInfo.PropertyType == typeof(DateTime) || PropertyInfo.PropertyType == typeof(DateTime?))
{
dateColumns.Add(datecolumn);
}
datecolumn++;
}
// Create the file using the FileInfo object
var file = new FileInfo(outputDir + fileName);
//create new excel package and save it
using (var package = new ExcelPackage())
{
//create new worksheet
var worksheet = package.Workbook.Worksheets.Add("Results");
// add headers
worksheet.Cells["A1"].LoadFromCollection(data, true);
//format date field
dateColumns.ForEach(item => worksheet.Column(item).Style.Numberformat.Format = "dd-mm-yyyy");
// auto size columns
worksheet.Cells.AutoFitColumns();
//save package
package.SaveAs(file);
}
你可以試試,如果你想使用 AM/PM
worksheet.Cells[1].Style.Numberformat.Format = "dd/MM/yyyy HH:mm:ss AM/PM";
繼采用 IEnumerable的非常好的Generic 解決方案之后,我們不得不更進一步,為不同的屬性顯示不同的日期格式。 例如,某些列需要顯示為dd/MM/yyyy
而其他列需要顯示為dd/MM/yyyy hh:mm
。
所以我們在我們的屬性中添加了一個帶有DataFormatString
( 代表DateTime
格式)的DisplayFormat
注釋,如下所示:
using System.ComponentModel.DataAnnotations;
...
[DisplayName("Download Date")]
[DisplayFormat(DataFormatString = "dd/MM/yyyy hh:mm")]
public string DownloadDate { get; set; }
...
然后借用IEnumerable 的通用解決方案......我們在迭代數據對象的屬性時從DisplayFormat
注釋中取出日期格式字符串:
public void FormatDateColumns(ExcelWorksheet worksheet, IEnumerable<IResult> data)
{
// Dictionary 'key' contains the Index of the column that contains DateTime data
// Dictionary 'value' contains the DateTime format for that column
Dictionary<int, string> dateColumns = new Dictionary<int, string>();
int dateColumnIndex = 1;
// find all the DateTime/DateTime? columns in the data object
foreach (var PropertyInfo in data.FirstOrDefault().GetType().GetProperties())
{
if (PropertyInfo.PropertyType == typeof(DateTime) || PropertyInfo.PropertyType == typeof(DateTime?))
{
string dateTimeFormat = Constants.DefaultDateTimeFormat;
// attempt to get a DataFormatString from a DisplayFormat annotation which may be decorating the Property
// looking for an annotation something like [DisplayFormat(DataFormatString = "dd-MM-yyyy hh:mm")]
if (PropertyInfo.CustomAttributes != null)
{
var dislayFormatAttribute = PropertyInfo.CustomAttributes.Where(x => x.AttributeType.Name == "DisplayFormatAttribute").FirstOrDefault();
if (dislayFormatAttribute != null && dislayFormatAttribute.NamedArguments != null && dislayFormatAttribute.NamedArguments.Count > 0)
{
var displayFormatArg = dislayFormatAttribute.NamedArguments.First();
if (displayFormatArg != null && displayFormatArg.TypedValue != null && displayFormatArg.TypedValue.Value != null)
{
// NOTE: there is probably an easier way to get at this value?
dateTimeFormat = displayFormatArg.TypedValue.Value.ToString();
}
}
}
dateColumns.Add(dateColumnIndex, dateTimeFormat);
}
dateColumnIndex++;
}
if (dateColumns.Count > 0)
{
// apply the formatting
dateColumns.ToList().ForEach(item => worksheet.Column(item.Key).Style.Numberformat.Format = item.Value);
}
}
我想補充一點,格式的設置是我的解決方案。 但是,在我將 value 屬性設置為 DateTime 對象而不是字符串之前,我無法讓它工作。 這是使一切順利的關鍵。
我有一個類似的問題,即使我正確設置了日期並將正確的數字格式應用於包含日期的單元格,我還是看到了日期的數字表示。
事實證明,在那之后,我應用了一種樣式,有效地重置了我的格式。
代碼是這樣的:
ws.Cells["A3"].Style.Numberformat.Format =
System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
ws.Cells["A3"].Value = New DateTime(2021, 10, 15, 23, 16, 0).ToOADate();
后來,我有:
ws.Cells("A3").StyleName = colStyle //colstyle is a style created earlier
為了解決這個問題,我需要在設置樣式后應用NumberFormat.Format
。
一些新聞:
ws.Cells["A3"].Style.Numberformat.Format = "[$-en-US]yyyy-mmm-dd";
ws.Cells["A3"].Formula = "=DATE(2014,10,5)";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.