我正在寻找一种创建日历并将其插入使用C#创建的Word文档中的方法。当前,我正在使用Microsoft.Office.Interop.Word库。解决此问题的唯一方法是创建5x7表并将其插入文档中。然后,我遍历每一行和每个单元格,以便给该单元格一个“日/月”格式的日期。
理想情况下,我希望日期位于该单元格的右上角(右对齐),然后在该日期下方但在同一单元格(左对齐)中插入不同的信息。
下面将附上我的代码,是否有人建议如何最好地解决此问题?除了创建模板并使用模板之外。
Microsoft.Office.Interop.Word.Application windowsWord = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document document = windowsWord.Documents.Add(ref missing, ref missing, ref missing, ref missing);
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
object styleHeading1 = "Heading 1";
para1.Range.set_Style(ref styleHeading1);
para1.Range.Text = "Some Location Text";
para1.Range.InsertParagraphAfter();
Table firstTable = document.Tables.Add(para1.Range, rowCount, 7, ref missing, ref missing);
firstTable.Borders.Enable = 1;
foreach (Row row in firstTable.Rows)
{
foreach (Cell cell in row.Cells)
{
if (cell.RowIndex == 1) //Populates the Days in Text i.e. Sun, Mon, Tues
{
cell.Range.Text = Days[cell.ColumnIndex - 1].Value;
cell.Range.Font.Bold = 1;
cell.Range.Font.Name = "verdana";
cell.Range.Font.Size = 10;
cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
}
else if (cell.RowIndex == 2) //Determines which column we should start populating the calendar from. This should only occur in the first non heading row
{
int dayOfWeek = (int)StartDate.DayOfWeek;
if (dateMarkingStarted)
{
var currentDate = StartDate.AddDays(daysCount);
cell.Range.Text = string.Format("{0}/{1}", currentDate.Month, currentDate.Day);
daysCount += 1;
}
else if (dayOfWeek == cell.ColumnIndex)
{
cell.Range.Text = string.Format("{0}/{1}", StartDate.Month, StartDate.Day);
dateMarkingStarted = true;
}
else //Otherwise populate cells with date accordingly
{
var currentDate = StartDate.AddDays(daysCount);
cell.Range.Text = string.Format("{0}/{1}", currentDate.Month, currentDate.Day);
daysCount += 1;
}
}
}