将数据写入Excel时如何设置正确的日期格式
我使用 Office 互操作将数据表导出到 Excel 文件。问题是,Excel 本身不识别日期,而是显示数字。在另一种情况下,我传递一个字符串,然后它将其识别为日期。在这两种情况下,数据都是混乱的。
我尝试了 NumberFormat @ ,它应该以文本格式存储单元格,但它也不起作用。
Application app = new Application();
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
app.EnableAnimations = false;
app.EnableAutoComplete = false;
app.EnableSound = false;
app.EnableTipWizard = false;
app.ErrorCheckingOptions.BackgroundChecking = false;
Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
Range rng = ws.Cells[j+2, i+1]as Range;
rng.Value2 = dt.Rows[j][i].ToString();
rng.NumberFormat = "@";
}
}
wb.SaveAs(filename, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
wb.Close(false, Missing.Value, Missing.Value);
app.Workbooks.Close();
app.Application.Quit();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
ws = null;
wb = null;
app = null;
GC.Collect();
为什么我的 NumberFormat @ 不起作用? Textformat 显示的所有内容不应该与我输入的内容相同吗?
Iam exporting a DataTable to an Excel-file using office interop. The problem is, that Excel does not recognize dates as such, but instead it displays numbers. In another case I pass a string which it then recognizes as a date. In both cases the data is messed up.
I tried NumberFormat @ which is supposed to store the cell in text format, but it didn't work either.
Application app = new Application();
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
app.EnableAnimations = false;
app.EnableAutoComplete = false;
app.EnableSound = false;
app.EnableTipWizard = false;
app.ErrorCheckingOptions.BackgroundChecking = false;
Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
Range rng = ws.Cells[j+2, i+1]as Range;
rng.Value2 = dt.Rows[j][i].ToString();
rng.NumberFormat = "@";
}
}
wb.SaveAs(filename, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
wb.Close(false, Missing.Value, Missing.Value);
app.Workbooks.Close();
app.Application.Quit();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
ws = null;
wb = null;
app = null;
GC.Collect();
Why doesn't my NumberFormat @ work? Shouldn't Textformat display everything the same as I put it in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
您是否尝试将整个列格式化为日期列?像这样的事情:
您可以尝试的另一件事是在将文本加载到 Excel 单元格之前在字符串表达式之前打一个勾(不确定这是否重要,但在直接将文本键入单元格时它可以工作)。
Did you try formatting the entire column as a date column? Something like this:
The other thing you could try would be putting a single tick before the string expression before loading the text into the Excel cell (not sure if that matters or not, but it works when typing text directly into a cell).
尝试使用
并将其作为双精度值放入单元格中。 Mac 系统上的 Excel 可能会出现问题(它使用不同的日期时间 --> 双重转换),但它在大多数情况下应该可以正常工作。
希望这有帮助。
Try using
And putting that as a double in the cell. There could be issues with Excel on Mac Systems (it uses a different datetime-->double conversion), but it should work well for most cases.
Hope this helps.
这对我有用:
注意日期之前添加的刻度线。
This worked for me:
Note the tick mark added before the date.
要按 Excel 单元格中的代码日期格式化,请尝试以下操作:
此后,您可以将日期时间值设置为特定单元格
如果您想设置整个列,请尝试以下操作:
Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[numberRow, numberColumn];
To format by code Date in Excel cells try this:
After this you can set the DateTime value to specific cell
If you want to set entire column try this:
Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[numberRow, numberColumn];
我知道这个问题很老了,但是通过 VSTO 用日期填充 Excell 单元格有一些问题。
格式化整个列不对我有用。
即使是微软的这种方法也不起作用:http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.namedrange.numberformat.aspx
例如,我从 SQL Analysis Server 返回的日期,我必须翻转它们,然后格式化它们:
否则使用日期的公式将不起作用 - 单元格 C4 中的公式与 C3 相同:
I know this question is old but populating Excell Cells with Dates via VSTO has a couple of gotchas.
Formatting the entire column did NOT work for me.
Not even this approach from Microsoft worked: http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.namedrange.numberformat.aspx
For example the dates I am getting come back from SQL Analysis Server and I had to flip them and then format them:
Otherwise formula's using Dates doesn't work - the formula in cell C4 is the same as C3:
稍微扩展一下@Assaf的答案,为了正确应用格式,我还必须在格式生效之前通过
.ToOADate()
函数转换DateTime
。您可以逐个单元格地执行此操作:或者您可以将格式应用于整个列:
Expanding slightly on @Assaf answer, to apply formatting correctly I also had to convert the
DateTime
via the.ToOADate()
function before the formatting took effect. You can do this on a cell by cell basis:Or you can apply the formatting to the entire column:
老问题但仍然相关。我生成了一个字典,它为每个区域获取适当的日期时间格式,这是我生成的帮助器类:
https://github.com/anakic/ExcelDateTimeFormatHelper/blob/master/FormatHelper.cs
FWIW这就是我的做法:
Old question but still relevant. I've generated a dictionary that gets the appropriate datetime format for each region, here is the helper class I generated:
https://github.com/anakic/ExcelDateTimeFormatHelper/blob/master/FormatHelper.cs
FWIW this is how I went about it:
这对我有用:
This worked for me:
希望这有帮助
Hope this help
尝试这个解决方案,在我的软件中工作得很好:
Try this solution, in my softwarew work very well:
这是一个旧线程。到了这个时候,人们要么使用 OpenXML。 OpenXML 好多了。好吧,许多像我这样的人都陷入困境,因为最初的开发人员使用互操作性。
我也经历了同样的挣扎几个小时。我已经尝试过这里的所有内容和其他用法。它仍然给了我数字表示。
然后我发现风格是我定的。风格属性毁了一切。我刚刚添加了 NumberFormat 属性,
这就是我所做的。有用
This is an old thread. By this time, people either use OpenXML. OpenXML is much better. Well, many people like me are stuck because the initial developers use the interops.
I had same struggle for couple hours. I have tried everything here and other usage. It still gave me numerical representation.
Then I found out that I set the style. The style property ruined everything. I just added the NumberFormatproperty
Here is what I did. It works
这取决于最后的问题。就我而言,我两者都有,这需要两种解决方案。
看一下下图,在元素 [4, 3] 中我有一个通用的 Date,所以通用的 C# 方法 DateTime.TryParse(formatted_target, out temptime);工作正常。
元素 [4, 5] 和[4, 6],显示在 Excel 端,仅包含时间和自定义格式(hh:mm,因此我们只能在 Excel 端的单元格中看到时间,但单元格本身包含完整的日期和时间对象) ,所以我们必须考虑到它们是用OLE自动化格式表达的,所以我们必须解析它们,所以之前将字符串解析为double; DateTime.FromOADate(Double.TryParse(item[4, 5]) 工作正常。
It depends on the issue at the End. In my case I had both, that required both solutions.
Take a look on the following image, in element [4, 3] I've a common Date, so the common C# method DateTime.TryParse(formatted_target, out temptime); works fine.
Elements [4, 5] & [4, 6], are shown on Excel side, with time only, and a custom format (hh:mm so we see only the time in the cell on Excel side, but the cell itself contains a complete date & time object), so we've to parse them considering they are expressed in OLE Automation format, so parsing the string as double before; DateTime.FromOADate(Double.TryParse(item[4, 5]) works fine.
就我而言,我得到了文本格式的日期(dd/MM/yyyy)。
当我将它传递给 Excel 时,有时它没问题,但有时它会变成 MM/dd/yyyy(当日期小于 12 时)。经过几次尝试和失败后,我找到了一种可行的方法。
我将日期作为字符串传递给 Excel 的格式是 yyyy/MM/dd。
这里有一些有用的代码示例。如何检查字符串是否为日期以及如何重新格式化它。
In my case I got dates in text format (dd/MM/yyyy).
When I pass it to Excel sometimes it is OK but sometimes it becomes MM/dd/yyyy (when day is less then 12). After few try-and-fail I found a way that works OK.
The format that works for me to pass a date as string to Excel is yyyy/MM/dd.
Here some usefull code samples. How to check if a string is a date and how to reformat it.