我有一个简单的代码,它将一个月的日期(DD/MM/YYYY)
设置为Column
in Excel
DateTime date = new DateTime(int.Parse(year.Text), int.Parse(month.Text), 1); //year.Text & month.Text are just the month and year from controls in the form.
for (int j = 7; j < daysInMonth + 7; j++)
{
sheet.get_Range("A" + j).Value = date.ToShortDateString();
date.AddDays(1.0);
}
其结果是:
01/2015
01/02/2015
01/03/2015
01/04/2015
01/05/2015
01/06/2015
01/07/2015
01/08/2015
01/09/2015
2015年10月1日
2015年11月1日
2015年12月1日
2015年1月13日
14/01/2015
2015年1月15日
..。
因此,只有1到12是有问题的。
编辑:
int daysInMonth = DateTime.DaysInMonth(int.Parse(year.Text), int.Parse(month.Text));
发布于 2015-10-25 16:55:22
问题是,在for-循环的每一次迭代之后,都不会更新日期。我是说你这样做是错误的:
date.AddDays(1.0);//这将返回一个值,但永远不会将它分配给日期本身。
你应该用这样的方法:
date = date.AddDays(1.0);
更新:上面的部分是您的代码中的一个小问题。主要问题是Excel本身。当您将日期传递给13岁以下的日期时,无论您提供给它的格式如何,它都会混淆它是月还是日。
解决方案:将日期存储为1900年1月1日(办公室支助)之后的天数。因此,您可以根据该格式设置单元格的值,然后将单元格的数字格式更改为通常设置为"DD/MM/YYYY“的格式。
从date:获得整数值的函数:
private int convertDateTime(DateTime input)
{
DateTime start = new DateTime(1900, 1, 1);
return (int)(input - start).TotalDays + 2; //This is some calibration with the above mentioned Office article
}
现在,您可以像这样使用代码::
DateTime date = new DateTime(int.Parse(year.Text), int.Parse(month.Text), 1); //year.Text & month.Text are just the month and year from controls in the form.
for (int j = 7; j < daysInMonth + 7; j++)
{
Range cell = sheet.get_Range("A" + j);
cell.Value = convertDateTime(date);
cell.NumberFormat = "DD/MM/YYYY";
date = date.AddDays(1.0);
}
发布于 2015-10-25 17:48:22
尝试计数循环中的单元格位置,并在将其设置为工作表之前增加日期,如下所示:
DateTime date = new DateTime(int.Parse(year.Text), int.Parse(month.Text), 1);
for (int j = 0; j < daysInMonth; j++)
{
// Skip increasing the first date
if (j > 0) {
date = date.AddDays(1.0);
}
// Set the correct date to the sheet
sheet.get_Range("A" + (j + 7)).Value = date.ToString(@"dd/MM/yyyy");
}
https://stackoverflow.com/questions/33332215
复制相似问题