月份、星期、生肖及图标.rar

    1. using Microsoft.Office.Core;
    2. using Microsoft.Office.Interop.Word;
    3. using System;
    4. using System.Diagnostics;
    5. using System.Globalization;
    6. using System.Reflection;
    7. using System.Windows.Forms;
    8. using Application = Microsoft.Office.Interop.Word.Application;
    9. using Shape = Microsoft.Office.Interop.Word.Shape;
    10. namespace CalendarGenerationTool
    11. {
    12. public partial class MainFrm : Form
    13. {
    14. public static string ImageLocal { get; set; }
    15. public static Application MSApp { get; set; }
    16. public static Document MSdoc { get; set; } = new Document();
    17. //由于使用的是COM库,因此有许多变量需要用Missing.Value代替
    18. public static object Nothing = Missing.Value;
    19. public MainFrm()
    20. {
    21. InitializeComponent();
    22. }
    23. private void MainFrm_Load(object sender, EventArgs e)
    24. {
    25. MyMethod.ImgFileInitialization();//图片路径初始化
    26. ImageLocal = $"{MyMethod.GetLocalDirectory()}\\CalendarToolImage";//文件路径
    27. CalendarYear.Text = DateTime.Now.Year.ToString();
    28. ChinaDate.MyYear = int.Parse(CalendarYear.Text);
    29. if (ChinaDate.MyYear == 1901) MyPBar.Maximum = CultureInfo.CurrentCulture.Calendar.GetDaysInYear(ChinaDate.MyYear) + 99;
    30. else if (ChinaDate.MyYear == 2101) MyPBar.Maximum = 56;
    31. else MyPBar.Maximum = CultureInfo.CurrentCulture.Calendar.GetDaysInYear(ChinaDate.MyYear) + 160;
    32. }
    33. private void AcceptOut_Click(object sender, EventArgs e)
    34. {
    35. try
    36. {
    37. Stopwatch stopWatch = new Stopwatch();
    38. stopWatch.Start();
    39. MyPBar.Value = 0;
    40. object DocPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}";
    41. DocPath = $"{DocPath}\\公元{ChinaDate.MyYear}({ChinaDate.GetEraYearZodiac(ChinaDate.MyYear)})年年历表({(Direction.Checked == true ? "竖向" : "横向")}).docx";
    42. MSApp = new Application
    43. {
    44. ScreenUpdating = false,
    45. DisplayAlerts = WdAlertLevel.wdAlertsNone
    46. };
    47. MSdoc = MSApp.Documents.Add(Missing.Value, ref Nothing, ref Nothing, ref Nothing);
    48. MSApp.ActiveWindow.View.ShowParagraphs = true;//隐藏段落标记
    49. //MSApp.Visible = true;
    50. MyPBar.PerformStep();
    51. //设置纸张方向
    52. MSdoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;//横向
    53. MyPBar.PerformStep();
    54. //if (Direction.Checked)
    55. // MSdoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait;//竖向
    56. //else
    57. // MSdoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;//横向
    58. //页边距设置
    59. MSdoc.PageSetup.TopMargin = MSApp.MillimetersToPoints(0);
    60. MSdoc.PageSetup.BottomMargin = MSApp.MillimetersToPoints(0);
    61. MSdoc.PageSetup.LeftMargin = MSApp.MillimetersToPoints(0);
    62. MSdoc.PageSetup.RightMargin = MSApp.MillimetersToPoints(0);
    63. MyPBar.PerformStep();
    64. //行距设置
    65. MSApp.Selection.WholeStory();
    66. MSApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;
    67. MSApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;
    68. MSApp.Selection.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceAtLeast;
    69. MSApp.Selection.ParagraphFormat.LineSpacing = 0.7f;
    70. MyPBar.PerformStep();
    71. //添加7行9列的表格
    72. Table TabDad = MSdoc.Tables.Add(MSApp.Selection.Range, 7, 9, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
    73. TabDad.PreferredWidth = MSApp.MillimetersToPoints(297);//设置表表格宽度
    74. //设置单元格水平垂直居中对齐
    75. TabDad.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
    76. TabDad.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
    77. MyPBar.PerformStep();
    78. //设置单元格边距
    79. SetPadding(TabDad);
    80. MyPBar.PerformStep();
    81. //设置行高
    82. TabDad.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitFixed);
    83. float[] rowhig = { 19f, 17.5f, 42f, 21.4f, 42f, 21.4f, 42f };
    84. for (int i = 1; i <= TabDad.Rows.Count; i++)
    85. {
    86. Row row = TabDad.Rows[i];
    87. SetTabRowHig(row, rowhig[i - 1]);
    88. }
    89. TabDad.Rows.AllowBreakAcrossPages = 0;
    90. MyPBar.PerformStep();
    91. //设置行高
    92. float[] colwid = { 14.6f, 56f, 14.6f, 56f, 14.6f, 56f, 14.6f, 56f, 14.6f };
    93. for (int i = 1; i <= TabDad.Columns.Count; i++)
    94. {
    95. TabDad.Columns[i].PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPoints;
    96. TabDad.Columns[i].PreferredWidth = MSApp.MillimetersToPoints(colwid[i - 1]);
    97. }
    98. MyPBar.PerformStep();
    99. //设置表格无轮廓
    100. TabDad.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
    101. TabDad.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleNone;
    102. MyPBar.PerformStep();
    103. //第一行合并,文本水平垂直居中
    104. TabDad.Rows[1].Cells.Merge();
    105. TabDad.Rows[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
    106. TabDad.Rows[1].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
    107. MyPBar.PerformStep();
    108. //在第一行插入文本框
    109. Shape shp = MSdoc.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, (float)((1 - 60) * 72 / 25.4), (float)(1 * 72 / 25.4), (float)(200 * 72 / 25.4), (float)(12 * 72 / 25.4), TabDad.Cell(1, 1).Range);
    110. shp.WrapFormat.Type = WdWrapType.wdWrapInline;
    111. shp.Name = "YearTBox";
    112. shp.Line.Visible = MsoTriState.msoFalse;//无轮廓
    113. MSApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//设置文本框架水平对齐方式
    114. MyPBar.PerformStep();
    115. ////设置文本框内部边距
    116. shp.TextFrame.MarginBottom = 0f;
    117. shp.TextFrame.MarginLeft = 0f;
    118. shp.TextFrame.MarginRight = 0f;
    119. shp.TextFrame.MarginTop = 0f;
    120. MyPBar.PerformStep();
    121. ////设置文本框填充颜色
    122. shp.Fill.BackColor.RGB = (int)XlRgbColor.xlLightGray;
    123. //shp.TextFrame.ContainingRange.HighlightColorIndex = WdColorIndex.wdGray25;
    124. shp.TextFrame.TextRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//设置文本框架中文本的水平对齐方式
    125. shp.TextFrame.VerticalAnchor = MsoVerticalAnchor.msoAnchorMiddle;//设置文本框架中文本的垂直居中对齐方式
    126. MyPBar.PerformStep();
    127. ////设置文本框行距
    128. shp.TextFrame.TextRange.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
    129. shp.TextFrame.TextRange.ParagraphFormat.LineSpacing = 32f;//设置行距
    130. MyPBar.PerformStep();
    131. //设置字体大小及字体名
    132. shp.TextFrame.TextRange.Font.Size = 23f;//设置字体大小
    133. shp.TextFrame.TextRange.Font.Name = "微软雅黑";//设置字体名
    134. shp.TextFrame.TextRange.Text = $"公元{ChinaDate.MyYear}({ChinaDate.GetEraYearZodiac(ChinaDate.MyYear)})年年历表";
    135. MyPBar.PerformStep();
    136. //InsertImg(TabDad, MyPBar);//插入月份星期图片
    137. InsertDateTab(TabDad, MyPBar);
    138. //移动光标
    139. object unite = WdUnits.wdStory;
    140. MSApp.Selection.EndKey(ref unite, ref Nothing);//将光标移到文本末尾
    141. MSApp.Selection.Font.Size = 1f;
    142. //插入生肖图片
    143. string imgpath = $"{ImageLocal}\\{ChinaDate.GetChineseZodiac(ChinaDate.MyYear)}1.jpg";
    144. Shape Zodiac = MSdoc.Shapes.AddPicture(imgpath, Nothing, Nothing, 0, (float)(206 * 72 / 25.4), (float)(297 * 72 / 25.4), (float)(210 * 72 / 25.4), Nothing);
    145. Zodiac.WrapFormat.Type = WdWrapType.wdWrapBehind;//嵌入型
    146. Zodiac.LayoutInCell = 0;//设置图片的表格单元格中的版式
    147. Zodiac.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;//设置横向对齐于页面
    148. Zodiac.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;//设置垂直对齐于页面
    149. Zodiac.Top = (float)WdShapePosition.wdShapeCenter;//图片上下居中
    150. Zodiac.Left = (float)WdShapePosition.wdShapeCenter;//图片左右居中
    151. //Zodiac.Width = MSApp.MillimetersToPoints(297f);
    152. //Zodiac.Height = MSApp.MillimetersToPoints(210f);
    153. MSApp.ScreenUpdating = true;
    154. MSApp.DisplayAlerts = WdAlertLevel.wdAlertsMessageBox;
    155. MSApp.ScreenRefresh();
    156. object docformat = WdSaveFormat.wdFormatDocumentDefault;
    157. MSdoc.SaveAs(ref DocPath, ref docformat, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
    158. MSdoc.Close();
    159. MyPBar.PerformStep();
    160. stopWatch.Stop();
    161. TimeSpan tml = stopWatch.Elapsed;
    162. string elapsedTime = string.Format("{0:00} 时 {1:00} 分 {2:00} 秒 {3:00}", tml.Hours, tml.Minutes, tml.Seconds, tml.Milliseconds / 10);
    163. MessageBox.Show($"{ChinaDate.MyYear}年日历制作完成,共耗时:{elapsedTime},感谢使用!");
    164. Process.Start("Explorer.exe", $"/select,{DocPath}");
    165. }
    166. catch (Exception)
    167. {
    168. throw;
    169. }
    170. finally
    171. {
    172. MSApp.Quit();
    173. }
    174. }
    175. private static void SetPadding(Table TabDad)
    176. {
    177. //设置单元格边距
    178. TabDad.TopPadding = MSApp.MillimetersToPoints(0);
    179. TabDad.BottomPadding = MSApp.MillimetersToPoints(0);
    180. TabDad.LeftPadding = MSApp.MillimetersToPoints(0);
    181. TabDad.RightPadding = MSApp.MillimetersToPoints(0);
    182. TabDad.Spacing = 0;
    183. TabDad.AllowPageBreaks = true;
    184. TabDad.AllowAutoFit = false;//不允许调整单元格间距
    185. }
    186. private static void SetTabRowHig(Row row, float height)
    187. {
    188. row.HeightRule = WdRowHeightRule.wdRowHeightExactly;
    189. row.Height = MSApp.MillimetersToPoints(height);
    190. }
    191. private static void InsertDateTab(Table tab, ProgressBar MyPBar)
    192. {
    193. Range[] monthrags =
    194. {
    195. tab.Cell(3, 2).Range, tab.Cell(3, 4).Range, tab.Cell(3, 6).Range, tab.Cell(3, 8).Range,
    196. tab.Cell(5, 2).Range, tab.Cell(5, 4).Range, tab.Cell(5, 6).Range, tab.Cell(5, 8).Range,
    197. tab.Cell(7, 2).Range, tab.Cell(7, 4).Range, tab.Cell(7, 6).Range, tab.Cell(7, 8).Range,
    198. };
    199. int MMin = 1, MMax = 13;
    200. if (ChinaDate.MyYear == 1901) MMin = 2;
    201. else if (ChinaDate.MyYear == 2101) MMax = 2;
    202. for (int Mth = MMin; Mth < MMax; Mth++)//(int i = 3; i < 8; i += 2)
    203. {
    204. Range wdrag = monthrags[Mth - 1];
    205. Table tbl = MSdoc.Tables.Add(wdrag, 1, 7, ref Nothing, ref Nothing);
    206. tbl.Select();
    207. object rows = 11;
    208. MSApp.Selection.InsertRowsBelow(ref rows);
    209. //设置表格总宽度
    210. tbl.PreferredWidth = MSApp.MillimetersToPoints(56);
    211. //设置表格每列宽度
    212. tbl.Columns.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPoints;
    213. tbl.Columns.PreferredWidth = MSApp.MillimetersToPoints(8);
    214. //设置单元格水平垂直居中对齐
    215. tbl.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
    216. tbl.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
    217. //设置单元格边距
    218. SetPadding(tbl);
    219. int days = DateTime.DaysInMonth(ChinaDate.MyYear, Mth), ds = 1, rw = 1;
    220. if (ChinaDate.MyYear == 1901 && Mth == 2)
    221. {
    222. //表示公历中1901年2月19日
    223. ds = 19;
    224. rw = ChinaDate.GetWeekOfMonth(new DateTime(ChinaDate.MyYear, Mth, ds)) * 2 - 1;
    225. }
    226. else if (ChinaDate.MyYear == 2101)
    227. {
    228. //表示公历上2101年1月28日
    229. days = 28;
    230. }
    231. for (int d = ds; d <= days; d++)
    232. {
    233. int col = ChinaDate.GetWeek(ChinaDate.MyYear, Mth, d) + 1;
    234. Range crg1 = tbl.Cell(rw, col).Range;
    235. crg1.Text = d.ToString();
    236. if (col == 1 || col == 7) crg1.Font.Color = WdColor.wdColorRed;
    237. Range crg2 = tbl.Cell(rw + 1, col).Range;
    238. string holidatstr = ChinaDate.GetDay(ChinaDate.MyYear, Mth, d, out bool isholiday);
    239. crg2.Text = holidatstr;
    240. if (isholiday)
    241. {
    242. crg2.Font.Color = WdColor.wdColorRed;
    243. if (holidatstr.Length == 4) crg2.Font.Scaling = 75;
    244. else if (holidatstr.Length == 5) crg2.Font.Scaling = 60;
    245. else if (holidatstr.Length == 6) crg2.Font.Scaling = 50;
    246. }
    247. if (col == 7) rw += 2;
    248. MyPBar.PerformStep();
    249. }
    250. //设置表格行高,字高行距等
    251. for (int k = 1; k <= tbl.Rows.Count; k++)
    252. {
    253. Row row = tbl.Rows[k];
    254. if (k % 2 == 1)
    255. {
    256. SetTabRowHig(row, 4f);
    257. ////设置文本框行距
    258. row.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
    259. row.Range.ParagraphFormat.LineSpacing = 12.5f;//设置行距
    260. row.Range.Font.Name = "Yu Gothic Medium";
    261. row.Range.Font.Size = 12.5f;
    262. row.Range.Font.Bold = 1;
    263. }
    264. else
    265. {
    266. SetTabRowHig(row, 3f);
    267. row.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
    268. row.Range.ParagraphFormat.LineSpacing = 7.5f;//设置行距
    269. row.Range.Font.Name = "Arial Unicode MS";
    270. row.Range.Font.Size = 7.5f;
    271. }
    272. MyPBar.PerformStep();
    273. }
    274. }
    275. }
    276. //private static void InsertImg(Table tab, ProgressBar MyPBar)
    277. //{
    278. // int k = 1;
    279. // List<string> imglist = new List<string>() { "Week", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" };
    280. // for (int i = 2; i < 13; i += 5)
    281. // {
    282. // for (int j = 2; j < 9; j += 2)
    283. // {
    284. // InlineShape ils1 = tab.Cell(i, j).Range.InlineShapes.AddPicture($"{ImageLocal}\\{imglist[k++]}.png", Nothing, Nothing, Nothing);
    285. // ils1.Width = MSApp.MillimetersToPoints(35f);
    286. // ils1.Height = MSApp.MillimetersToPoints(7f);
    287. // InlineShape ils2 = tab.Cell(i + 1, j).Range.InlineShapes.AddPicture($"{ImageLocal}\\{imglist[0]}.png", Nothing, Nothing, Nothing);
    288. // ils2.Width = MSApp.MillimetersToPoints(56f);
    289. // ils2.Height = MSApp.MillimetersToPoints(9f);
    290. // MyPBar.PerformStep();
    291. // }
    292. // }
    293. //}
    294. private void CalendarYear_SelectedValueChanged(object sender, EventArgs e)
    295. {
    296. if (MyPBar.Value > 0) MyPBar.Value = 0;
    297. ChinaDate.MyYear = int.Parse(CalendarYear.Text);
    298. if (ChinaDate.MyYear == 1901) MyPBar.Maximum = CultureInfo.CurrentCulture.Calendar.GetDaysInYear(ChinaDate.MyYear) + 99;
    299. else if (ChinaDate.MyYear == 2101) MyPBar.Maximum = 56;
    300. else MyPBar.Maximum = CultureInfo.CurrentCulture.Calendar.GetDaysInYear(ChinaDate.MyYear) + 160;
    301. }
    302. private void NowYear_Click(object sender, EventArgs e)
    303. {
    304. CalendarYear.Text = DateTime.Now.Year.ToString();
    305. }
    306. }
    307. }