月份、星期、生肖及图标.rar
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Windows.Forms;
using Application = Microsoft.Office.Interop.Word.Application;
using Shape = Microsoft.Office.Interop.Word.Shape;
namespace CalendarGenerationTool
{
public partial class MainFrm : Form
{
public static string ImageLocal { get; set; }
public static Application MSApp { get; set; }
public static Document MSdoc { get; set; } = new Document();
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
public static object Nothing = Missing.Value;
public MainFrm()
{
InitializeComponent();
}
private void MainFrm_Load(object sender, EventArgs e)
{
MyMethod.ImgFileInitialization();//图片路径初始化
ImageLocal = $"{MyMethod.GetLocalDirectory()}\\CalendarToolImage";//文件路径
CalendarYear.Text = DateTime.Now.Year.ToString();
ChinaDate.MyYear = int.Parse(CalendarYear.Text);
if (ChinaDate.MyYear == 1901) MyPBar.Maximum = CultureInfo.CurrentCulture.Calendar.GetDaysInYear(ChinaDate.MyYear) + 99;
else if (ChinaDate.MyYear == 2101) MyPBar.Maximum = 56;
else MyPBar.Maximum = CultureInfo.CurrentCulture.Calendar.GetDaysInYear(ChinaDate.MyYear) + 160;
}
private void AcceptOut_Click(object sender, EventArgs e)
{
try
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
MyPBar.Value = 0;
object DocPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}";
DocPath = $"{DocPath}\\公元{ChinaDate.MyYear}({ChinaDate.GetEraYearZodiac(ChinaDate.MyYear)})年年历表({(Direction.Checked == true ? "竖向" : "横向")}).docx";
MSApp = new Application
{
ScreenUpdating = false,
DisplayAlerts = WdAlertLevel.wdAlertsNone
};
MSdoc = MSApp.Documents.Add(Missing.Value, ref Nothing, ref Nothing, ref Nothing);
MSApp.ActiveWindow.View.ShowParagraphs = true;//隐藏段落标记
//MSApp.Visible = true;
MyPBar.PerformStep();
//设置纸张方向
MSdoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;//横向
MyPBar.PerformStep();
//if (Direction.Checked)
// MSdoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait;//竖向
//else
// MSdoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;//横向
//页边距设置
MSdoc.PageSetup.TopMargin = MSApp.MillimetersToPoints(0);
MSdoc.PageSetup.BottomMargin = MSApp.MillimetersToPoints(0);
MSdoc.PageSetup.LeftMargin = MSApp.MillimetersToPoints(0);
MSdoc.PageSetup.RightMargin = MSApp.MillimetersToPoints(0);
MyPBar.PerformStep();
//行距设置
MSApp.Selection.WholeStory();
MSApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;
MSApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;
MSApp.Selection.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceAtLeast;
MSApp.Selection.ParagraphFormat.LineSpacing = 0.7f;
MyPBar.PerformStep();
//添加7行9列的表格
Table TabDad = MSdoc.Tables.Add(MSApp.Selection.Range, 7, 9, WdDefaultTableBehavior.wdWord9TableBehavior, WdAutoFitBehavior.wdAutoFitFixed);
TabDad.PreferredWidth = MSApp.MillimetersToPoints(297);//设置表表格宽度
//设置单元格水平垂直居中对齐
TabDad.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
TabDad.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
MyPBar.PerformStep();
//设置单元格边距
SetPadding(TabDad);
MyPBar.PerformStep();
//设置行高
TabDad.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitFixed);
float[] rowhig = { 19f, 17.5f, 42f, 21.4f, 42f, 21.4f, 42f };
for (int i = 1; i <= TabDad.Rows.Count; i++)
{
Row row = TabDad.Rows[i];
SetTabRowHig(row, rowhig[i - 1]);
}
TabDad.Rows.AllowBreakAcrossPages = 0;
MyPBar.PerformStep();
//设置行高
float[] colwid = { 14.6f, 56f, 14.6f, 56f, 14.6f, 56f, 14.6f, 56f, 14.6f };
for (int i = 1; i <= TabDad.Columns.Count; i++)
{
TabDad.Columns[i].PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPoints;
TabDad.Columns[i].PreferredWidth = MSApp.MillimetersToPoints(colwid[i - 1]);
}
MyPBar.PerformStep();
//设置表格无轮廓
TabDad.Borders.InsideLineStyle = WdLineStyle.wdLineStyleNone;
TabDad.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleNone;
MyPBar.PerformStep();
//第一行合并,文本水平垂直居中
TabDad.Rows[1].Cells.Merge();
TabDad.Rows[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
TabDad.Rows[1].Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
MyPBar.PerformStep();
//在第一行插入文本框
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);
shp.WrapFormat.Type = WdWrapType.wdWrapInline;
shp.Name = "YearTBox";
shp.Line.Visible = MsoTriState.msoFalse;//无轮廓
MSApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//设置文本框架水平对齐方式
MyPBar.PerformStep();
////设置文本框内部边距
shp.TextFrame.MarginBottom = 0f;
shp.TextFrame.MarginLeft = 0f;
shp.TextFrame.MarginRight = 0f;
shp.TextFrame.MarginTop = 0f;
MyPBar.PerformStep();
////设置文本框填充颜色
shp.Fill.BackColor.RGB = (int)XlRgbColor.xlLightGray;
//shp.TextFrame.ContainingRange.HighlightColorIndex = WdColorIndex.wdGray25;
shp.TextFrame.TextRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//设置文本框架中文本的水平对齐方式
shp.TextFrame.VerticalAnchor = MsoVerticalAnchor.msoAnchorMiddle;//设置文本框架中文本的垂直居中对齐方式
MyPBar.PerformStep();
////设置文本框行距
shp.TextFrame.TextRange.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
shp.TextFrame.TextRange.ParagraphFormat.LineSpacing = 32f;//设置行距
MyPBar.PerformStep();
//设置字体大小及字体名
shp.TextFrame.TextRange.Font.Size = 23f;//设置字体大小
shp.TextFrame.TextRange.Font.Name = "微软雅黑";//设置字体名
shp.TextFrame.TextRange.Text = $"公元{ChinaDate.MyYear}({ChinaDate.GetEraYearZodiac(ChinaDate.MyYear)})年年历表";
MyPBar.PerformStep();
//InsertImg(TabDad, MyPBar);//插入月份星期图片
InsertDateTab(TabDad, MyPBar);
//移动光标
object unite = WdUnits.wdStory;
MSApp.Selection.EndKey(ref unite, ref Nothing);//将光标移到文本末尾
MSApp.Selection.Font.Size = 1f;
//插入生肖图片
string imgpath = $"{ImageLocal}\\{ChinaDate.GetChineseZodiac(ChinaDate.MyYear)}1.jpg";
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);
Zodiac.WrapFormat.Type = WdWrapType.wdWrapBehind;//嵌入型
Zodiac.LayoutInCell = 0;//设置图片的表格单元格中的版式
Zodiac.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;//设置横向对齐于页面
Zodiac.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;//设置垂直对齐于页面
Zodiac.Top = (float)WdShapePosition.wdShapeCenter;//图片上下居中
Zodiac.Left = (float)WdShapePosition.wdShapeCenter;//图片左右居中
//Zodiac.Width = MSApp.MillimetersToPoints(297f);
//Zodiac.Height = MSApp.MillimetersToPoints(210f);
MSApp.ScreenUpdating = true;
MSApp.DisplayAlerts = WdAlertLevel.wdAlertsMessageBox;
MSApp.ScreenRefresh();
object docformat = WdSaveFormat.wdFormatDocumentDefault;
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);
MSdoc.Close();
MyPBar.PerformStep();
stopWatch.Stop();
TimeSpan tml = stopWatch.Elapsed;
string elapsedTime = string.Format("{0:00} 时 {1:00} 分 {2:00} 秒 {3:00}", tml.Hours, tml.Minutes, tml.Seconds, tml.Milliseconds / 10);
MessageBox.Show($"{ChinaDate.MyYear}年日历制作完成,共耗时:{elapsedTime},感谢使用!");
Process.Start("Explorer.exe", $"/select,{DocPath}");
}
catch (Exception)
{
throw;
}
finally
{
MSApp.Quit();
}
}
private static void SetPadding(Table TabDad)
{
//设置单元格边距
TabDad.TopPadding = MSApp.MillimetersToPoints(0);
TabDad.BottomPadding = MSApp.MillimetersToPoints(0);
TabDad.LeftPadding = MSApp.MillimetersToPoints(0);
TabDad.RightPadding = MSApp.MillimetersToPoints(0);
TabDad.Spacing = 0;
TabDad.AllowPageBreaks = true;
TabDad.AllowAutoFit = false;//不允许调整单元格间距
}
private static void SetTabRowHig(Row row, float height)
{
row.HeightRule = WdRowHeightRule.wdRowHeightExactly;
row.Height = MSApp.MillimetersToPoints(height);
}
private static void InsertDateTab(Table tab, ProgressBar MyPBar)
{
Range[] monthrags =
{
tab.Cell(3, 2).Range, tab.Cell(3, 4).Range, tab.Cell(3, 6).Range, tab.Cell(3, 8).Range,
tab.Cell(5, 2).Range, tab.Cell(5, 4).Range, tab.Cell(5, 6).Range, tab.Cell(5, 8).Range,
tab.Cell(7, 2).Range, tab.Cell(7, 4).Range, tab.Cell(7, 6).Range, tab.Cell(7, 8).Range,
};
int MMin = 1, MMax = 13;
if (ChinaDate.MyYear == 1901) MMin = 2;
else if (ChinaDate.MyYear == 2101) MMax = 2;
for (int Mth = MMin; Mth < MMax; Mth++)//(int i = 3; i < 8; i += 2)
{
Range wdrag = monthrags[Mth - 1];
Table tbl = MSdoc.Tables.Add(wdrag, 1, 7, ref Nothing, ref Nothing);
tbl.Select();
object rows = 11;
MSApp.Selection.InsertRowsBelow(ref rows);
//设置表格总宽度
tbl.PreferredWidth = MSApp.MillimetersToPoints(56);
//设置表格每列宽度
tbl.Columns.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPoints;
tbl.Columns.PreferredWidth = MSApp.MillimetersToPoints(8);
//设置单元格水平垂直居中对齐
tbl.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
tbl.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
//设置单元格边距
SetPadding(tbl);
int days = DateTime.DaysInMonth(ChinaDate.MyYear, Mth), ds = 1, rw = 1;
if (ChinaDate.MyYear == 1901 && Mth == 2)
{
//表示公历中1901年2月19日
ds = 19;
rw = ChinaDate.GetWeekOfMonth(new DateTime(ChinaDate.MyYear, Mth, ds)) * 2 - 1;
}
else if (ChinaDate.MyYear == 2101)
{
//表示公历上2101年1月28日
days = 28;
}
for (int d = ds; d <= days; d++)
{
int col = ChinaDate.GetWeek(ChinaDate.MyYear, Mth, d) + 1;
Range crg1 = tbl.Cell(rw, col).Range;
crg1.Text = d.ToString();
if (col == 1 || col == 7) crg1.Font.Color = WdColor.wdColorRed;
Range crg2 = tbl.Cell(rw + 1, col).Range;
string holidatstr = ChinaDate.GetDay(ChinaDate.MyYear, Mth, d, out bool isholiday);
crg2.Text = holidatstr;
if (isholiday)
{
crg2.Font.Color = WdColor.wdColorRed;
if (holidatstr.Length == 4) crg2.Font.Scaling = 75;
else if (holidatstr.Length == 5) crg2.Font.Scaling = 60;
else if (holidatstr.Length == 6) crg2.Font.Scaling = 50;
}
if (col == 7) rw += 2;
MyPBar.PerformStep();
}
//设置表格行高,字高行距等
for (int k = 1; k <= tbl.Rows.Count; k++)
{
Row row = tbl.Rows[k];
if (k % 2 == 1)
{
SetTabRowHig(row, 4f);
////设置文本框行距
row.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
row.Range.ParagraphFormat.LineSpacing = 12.5f;//设置行距
row.Range.Font.Name = "Yu Gothic Medium";
row.Range.Font.Size = 12.5f;
row.Range.Font.Bold = 1;
}
else
{
SetTabRowHig(row, 3f);
row.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
row.Range.ParagraphFormat.LineSpacing = 7.5f;//设置行距
row.Range.Font.Name = "Arial Unicode MS";
row.Range.Font.Size = 7.5f;
}
MyPBar.PerformStep();
}
}
}
//private static void InsertImg(Table tab, ProgressBar MyPBar)
//{
// int k = 1;
// List<string> imglist = new List<string>() { "Week", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" };
// for (int i = 2; i < 13; i += 5)
// {
// for (int j = 2; j < 9; j += 2)
// {
// InlineShape ils1 = tab.Cell(i, j).Range.InlineShapes.AddPicture($"{ImageLocal}\\{imglist[k++]}.png", Nothing, Nothing, Nothing);
// ils1.Width = MSApp.MillimetersToPoints(35f);
// ils1.Height = MSApp.MillimetersToPoints(7f);
// InlineShape ils2 = tab.Cell(i + 1, j).Range.InlineShapes.AddPicture($"{ImageLocal}\\{imglist[0]}.png", Nothing, Nothing, Nothing);
// ils2.Width = MSApp.MillimetersToPoints(56f);
// ils2.Height = MSApp.MillimetersToPoints(9f);
// MyPBar.PerformStep();
// }
// }
//}
private void CalendarYear_SelectedValueChanged(object sender, EventArgs e)
{
if (MyPBar.Value > 0) MyPBar.Value = 0;
ChinaDate.MyYear = int.Parse(CalendarYear.Text);
if (ChinaDate.MyYear == 1901) MyPBar.Maximum = CultureInfo.CurrentCulture.Calendar.GetDaysInYear(ChinaDate.MyYear) + 99;
else if (ChinaDate.MyYear == 2101) MyPBar.Maximum = 56;
else MyPBar.Maximum = CultureInfo.CurrentCulture.Calendar.GetDaysInYear(ChinaDate.MyYear) + 160;
}
private void NowYear_Click(object sender, EventArgs e)
{
CalendarYear.Text = DateTime.Now.Year.ToString();
}
}
}