Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用EPPlus的Excel数据格式_C#_Epplus - Fatal编程技术网

C# 使用EPPlus的Excel数据格式

C# 使用EPPlus的Excel数据格式,c#,epplus,C#,Epplus,到目前为止,我的单元格格式有问题 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

到目前为止,我的单元格格式有问题

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";
如果你使用塔拉兹提到的公式。最后添加工作表.Calculate()。 参考文献

或者不使用公式,而是使用替代方法

private static decimal GetExcelDecimalValueForDate(DateTime date)
{
    DateTime start = new DateTime(1900, 1, 1);
    TimeSpan diff = date - start;
    return diff.Days + 2;
}

默认情况下,excel保存日期字段时,会将其保存为
numFormatId
14(查看xls中的xml文件)。这样可以确保打开文件时,任何国家/地区的日期格式都正确。 在Epplus中,对于excel,将年月日<代码>转换为<代码>numFormatId14。 这将确保在任何国家/地区打开文件时,日期将根据该国家/地区的短日期设置正确格式化。 还注意到
m/d/yy h:mm格式适用于任何国家/地区。

一些新闻:

ws.Cells[“A3”].Style.Numberformat.Format=“[$-en-US]yyyy-mmm-dd”
ws.Cells[“A3”]公式=“=日期(2014,10,5)”


采用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);
            }
//设置将用于格式化日期列的日期列列表
List dateColumns=new List();
//获取第一个索引器
int-datecolumn=1;
//循环遍历对象并获取datecolumns列表
foreach(data.FirstOrDefault().GetType().GetProperties()中的var PropertyInfo)
{
//检查属性是否为DateTime类型或可为Null的DateTime类型
if(PropertyInfo.PropertyType==typeof(DateTime)| | PropertyInfo.PropertyType==typeof(DateTime?)
{
dateColumns.Add(datecolumn);
}
datecolumn++;
}
//使用FileInfo对象创建文件
var file=newfileinfo(outputDir+fileName);
//创建新的excel包并保存它
使用(var package=new ExcelPackage())
{
//创建新工作表
var工作表=package.Workbook.Worksheets.Add(“结果”);
//添加标题
工作表.Cells[“A1”].LoadFromCollection(数据,true);
//格式化日期字段
dateColumns.ForEach(项=>工作表.Column(项).Style.Numberformat.Format=“dd-mm-yyyy”);
//自动调整列大小
worksheet.Cells.AutoFitColumns();
//保存包
package.SaveAs(文件);
}

我在转换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;
    }

如果你想使用AM/PM,你可以试试

   worksheet.Cells[1].Style.Numberformat.Format = "dd/MM/yyyy  HH:mm:ss AM/PM";

根据非常好的答案,我们必须更进一步,为不同的属性显示不同的日期格式。例如,一些列需要显示为
dd/MM/yyyy
,其他列需要显示为
dd/MM/yyyy hh:MM

因此,我们在属性中添加了一个带有
DataFormatString
()的
DisplayFormat
注释,如下所示:

using System.ComponentModel.DataAnnotations;
...
[DisplayName("Download Date")]
[DisplayFormat(DataFormatString = "dd/MM/yyyy hh:mm")]
public string DownloadDate { get; set; }
...
然后借用,在迭代数据对象的属性时,我们从
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);
    }
}
public void FormatDateColumns(Excel工作表,IEnumerable数据)
{
//字典“键”包含包含日期时间数据的列的索引
//字典“value”包含该列的日期时间格式
Dictionary dateColumns=新字典();
int-dateColumnIndex=1;
//查找数据对象中的所有DateTime/DateTime?列
foreach(data.FirstOrDefault().GetType().GetProperties()中的var PropertyInfo)
{
if(PropertyInfo.PropertyType==typeof(DateTime)| | PropertyInfo.PropertyType==typeof(DateTime?)
{
字符串dateTimeFormat=Constants.DefaultDateTimeFormat;
//尝试从可能装饰属性的DisplayFormat批注获取DataFormatString
//寻找类似[DisplayFormat(DataFormatString=“dd-MM-yyyy-hh:MM”)的注释
if(PropertyInfo.CustomAttributes!=null)
{
var dislayFormatAttribute=PropertyInfo.CustomAttributes.Where(x=>x.AttributeType.Name==“DisplayFormatAttribute”).FirstOrDefault();
如果(dislayFormatAttribute!=null&&dislayFormatAttribute.NamedArguments!=null&&dislayFormatAttribute.NamedArguments.Count>0)
{
var displayFormatArg=dislayFormatAttribute.NamedArguments.First();
if(displayFormatArg!=null&&displayFormatArg.TypedValue!=null&&displayFormatArg.TypedValue.Value!=null)
{
//注意:可能有更简单的方法来获取此值?
dateTimeFormat=displayFormatArg.TypedValue.Value.ToString();
}
}
}
添加(dateColumnIndex,dateTimeFormat);
}
dateColumnIndex++;
}
如果(dateColumns.Count>0)
{
//应用格式
dateColumns.ToList().ForEach(item=>sheet.Column(item.Key).Style.Numberformat.Format=item.Value);
}
}

我想补充一点,格式的设置是我的解决方案。但是,在将value属性设置为DateTime对象而不是字符串之前,我无法让它工作。这是使所有工作正常进行的关键。

我也遇到了类似的问题,尽管我正确设置了日期并对包含日期的单元格应用了正确的数字格式,但我看到了日期的数字表示形式

转向
using System.ComponentModel.DataAnnotations;
...
[DisplayName("Download Date")]
[DisplayFormat(DataFormatString = "dd/MM/yyyy hh:mm")]
public string DownloadDate { get; set; }
...
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);
    }
}
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