【问题标题】:Adding Date to Excel using Open XML [closed]使用 Open XML 将日期添加到 Excel [关闭]
【发布时间】:2014-04-29 21:49:13
【问题描述】:

我想使用 Open XML 将日期值插入到 Excel 文件中。

这是我的代码示例。

cell.CellValue = new CellValue(value.ToString());   
cell.DataType = new EnumValue<CellValues>(CellValues.Date);  

【问题讨论】:

  • 然后会发生什么?你有错误吗?如果是这样:什么错误?该值是否未添加到生成的 Excel 工作表中?尝试打开生成的 Excel 工作表时是否出现错误?您必须帮助我们在这里为您提供帮助!
  • 我看到了日期的第一部分。例如 24/01/2010,我在单元格中看到 24。
  • 关门了?为什么?我同意这个问题可以更好地描述,但如果你知道这是关于什么的,你会同意这是一个真实的问题,有一个真实的答案!

标签: excel openxml


【解决方案1】:

显然,DataType 应该省略!

我遇到了同样的问题,但只是设置 CellValue 就可以了!

cell.CellValue = new CellValue(value.ToOADate().ToString())

【讨论】:

    【解决方案2】:

    我得到了答案并与大家分享...

    像我们一样添加单元格..

     Cell cell =new Cell(){ cellReference=A1 }; //Or other necessary details
    
     //Add value to cell in Double Format  then convert it into string using ToString()
     cell.cellValue = new CellValue(DateTime.Now().ToDouble().ToString()); 
    
     //Set the data type as Number
     cell.DataType = new EnumValue<CellValues>(CellValues.Number);
    
     //Give its StyleIndex = 5 (default style index of date)
     cell.StyleIndex=5;
    

    这里我用过

    cell.StyleIndex=5;
    

    这是 Excel 中日期的默认样式索引。所以不需要添加所有的外部样式表

    享受:)

    【讨论】:

    【解决方案3】:

    以下对我们有用:

    c.CellValue = new CellValue(datetimeValue).ToOADate().ToString());
    c.DataType = CellValues.Number;
    c.StyleIndex = StyleDate;
    

    将 DataType 设置为 CellValues.Number,然后确保使用 CellFormats 中的适当样式索引格式化单元格。在我们的例子中,我们在工作表中构建了一个样式表,StyleDate 是样式表中 CellFormats 的索引。

    【讨论】:

    • 有趣的是,您在两个 StackOverflow 线程中引用了这段代码(早在 2012 年),但没有显示“StyleDate”的实际外观,因此读者实际上无法使用或学习来自您的代码!
    • @MikeGledhill 没错。很生气
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    相关资源
    最近更新 更多