Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do something for each value in Datetime Range C#

I’ve got the following Code

  public static IEnumerable<DateRange> GetWeekdayRange(DateTime startDate, DateTime endDate, DayOfWeek weekEndsOn = DayOfWeek.Sunday)
    {
        var currStartDate = startDate;
        var currDate = startDate;
        while (currDate < endDate)
        {
            while (currDate.DayOfWeek != weekEndsOn && currDate < endDate)
            {
                currDate = currDate.AddDays(1);
            }
            yield return new DateRange { WeekStartDate = currStartDate, WeekEndDate = currDate };
            currStartDate = currDate.AddDays(1);
            currDate = currStartDate;
        }
    }

    public struct DateRange
    {
        public DateTime WeekStartDate { get; set; }
        public DateTime WeekEndDate { get; set; }
    }

Then I add the values to fields in a word doc. Now I want to create a document for each WeekRange

var word = new Microsoft.Office.Interop.Word.Application();
        var template = word.Documents.Open($@"C:\Path\Template.docx");
var range = GetWeekdayRange(start, end);
        foreach (var val in range)
        {
            template.Variables["WocheVon"].Value = @$"{0:yyyy-MM-dd}";
            template.Variables["WocheBis"].Value = @$"{1:yyyy-MM-dd}";
            template.Variables["VollerName"].Value = fullName;
            template.Fields.Update();
            template.SaveAs(@$"C:\Path\{fullName}_{0:yyyy-MM-dd}_{1:yyyy-MM-dd}.docx");

        }
        template.Close();
        word.Quit();

start and end are datetimes from a datetimepicker.
This only creates a single doc, I need one for each WeekDayRange between start and end.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe someone has an idea of what I’m missing.

>Solution :

It seems to be missing this:

template.Variables["WocheVon"].Value = @$"{val.WeekStartDate:yyyy-MM-dd}";
template.Variables["WocheBis"].Value = @$"{val.WeekEndDate:yyyy-MM-dd}";

And this:

template.SaveAs(@$"C:\Path\{fullName}_{val.WeekStartDate:yyyy-MM-dd}_{val.WeekEndDate:yyyy-MM-dd}.docx");

You’re putting placeholders in the @$ and not the actual dates.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading