如何转换“双”到“datetime” Excel和c#之间 [英] How to convert "double" to "datetime" between Excel and c#
本文介绍了如何转换“双”到“datetime” Excel和c#之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里是我代码的一部分:
// c#code:
workSheet.Cells [1,1] == 2012/9/20; // asign2012/9/20到Excel中的单元格[1,1]
double d = workSheet.Cells [1,1] .value(); //默认情况下,Excel将返回11.17
Debug.Print(d.ToString()); // c#:d = 11.1777777777778
所以如何使输出成为2012/9/20再次?
我尝试了一些代码,但失败:
DateTime str = DateTime.FromOADate(d); // c#:str = 1/10/1900 4:16:00 AM
DateTime str = new DateTime((long)d); // c#:str = 1/1/0001 12:00:00 AM
解决方案
您可以尝试这样:
首先设置单元格中的格式:
ws.Cells [1,1] .Style.Numberformat.Format =yyyy / MM / dd;
然后将值设置为DateTime:
workSheet.Cells [1,1] = new DateTime(2012,9,20);
要获取价值,请使用以下内容:
double d = double.Parse(workSheet.Cells [1,1] .value());
DateTime conv = DateTime.FromOADate(d);
I have a c# program which needs to create an excel object, and do some operations, here are parts of my code:
// c# code:
workSheet.Cells[1, 1] = "=2012/9/20"; //asign "2012/9/20" to cell[1,1] in Excel
double d = workSheet.Cells[1, 1].value(); // by default, Excel will return 11.17
Debug.Print(d.ToString()); //c#: d = 11.1777777777778
so how to make the output become "2012/9/20" again?
I have tried some codes, but fail:
DateTime str = DateTime.FromOADate(d); //c#: str = 1/10/1900 4:16:00 AM
DateTime str = new DateTime((long)d); //c#: str = 1/1/0001 12:00:00 AM
解决方案
You can try this:
First set the format in the cell:
ws.Cells[1,1].Style.Numberformat.Format = "yyyy/MM/dd";
Then set value as DateTime:
workSheet.Cells[1, 1] =new DateTime(2012,9,20);
And to get value use the following:
double d = double.Parse(workSheet.Cells[1, 1].value());
DateTime conv = DateTime.FromOADate(d);
这篇关于如何转换“双”到“datetime” Excel和c#之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文