public void AddTable(string content, Model.Style style) { object defaultTableBehavior = Word.WdDefaultTableBehavior.wdWord9TableBehavior; object autofitbehavior = Word.WdAutoFitBehavior.wdAutoFitFixed; GoToTheEnd(); Word.Table tablea = null; if (!string.IsNullOrWhiteSpace(content)) { tablea = application.ActiveDocument.Tables.Add(application.Selection.Range, 1, 3, ref defaultTableBehavior, ref autofitbehavior); application.Selection.ParagraphFormat.SpaceBefore = 0f; application.Selection.ParagraphFormat.SpaceAfterAuto = 0; application.Selection.ParagraphFormat.FirstLineIndent = application.CentimetersToPoints(0.3f); GoToTheEnd(); } var tableb = application.ActiveDocument.Tables.Add(application.Selection.Range, 1, 2, ref defaultTableBehavior, ref autofitbehavior); application.Selection.ParagraphFormat.SpaceBefore = 0f; application.Selection.ParagraphFormat.SpaceAfterAuto = 0; application.Selection.ParagraphFormat.FirstLineIndent = application.CentimetersToPoints(0.3f); SetTableStyle(1, style); application.Selection.Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast; application.Selection.Rows.Height = application.CentimetersToPoints(1f); application.Selection.Columns.PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthAuto; application.Selection.Columns.PreferredWidth = 0; application.Selection.Cells.PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthAuto; application.Selection.Cells.PreferredWidth = 0; application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; if (tablea != null) { var cella = tablea.Cell(1, 1); cella.Width = 60f; cella.Range.Text = "抄送:"; var celld = tablea.Cell(1, 2); celld.Range.Text = content; } var cellc = tableb.Cell(1, 2); cellc.Range.Text = DateTime.Today.ToString("yyyy年MM月dd日") + "印发"; //cellc.Range.ShapeRange.Align(Microsoft.Office.Core.MsoAlignCmd.msoAlignRights, 0); cellc.Range.FitTextWidth = application.CentimetersToPoints(4.00f); var cellb = tableb.Cell(1, 1); cellb.Range.Text = "国网重庆市电力公司永川供电分公司办公室"; cellb.Range.ShapeRange.Align(Microsoft.Office.Core.MsoAlignCmd.msoAlignLefts, 0); //cellb.Range.FitTextWidth = application.CentimetersToPoints(1.22f); //row = application.Selection.Tables[1].Rows[2]; //row.Cells[1].Range.Text = "国网重庆市电力公司永川供电分公司办公室"; //row.Cells[1].Range.Application.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; //row.Cells[2].Range.Text = DateTime.Today.ToString("yyyy年MM月dd日")+"印发"; //row.Cells[2].Range.Application.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; }
private void createThesis() { buttonX3.Enabled = false; int start, end; MSWord.Paragraphs pgs = wordDoc.TablesOfContents[1].Range.Paragraphs; wordApp.Selection.SetRange(wordDoc.TablesOfContents[1].Range.End, wordDoc.TablesOfContents[1].Range.End); foreach (MSWord.Paragraph pa in pgs) { if (pa.Range.Text.Split('\t')[0].Trim() != "") { pa.Range.Hyperlinks[1].Follow(); //wordApp.Visible = false; start = wordApp.Selection.Range.End + 1; wordApp.Selection.SetRange(start, start); if (pa.Next() != null) { if (pa.Next().Range.Text.Trim() == "") { end = wordDoc.Content.End; } else { pa.Next().Range.Hyperlinks[1].Follow(); //wordApp.Visible = false; end = wordApp.Selection.Range.Start - 1; } wordApp.Selection.SetRange(start, end); } else { break; } try { if (wordApp.Selection.Range.Text.Trim() != "") { wordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 0; wordApp.Selection.ParagraphFormat.LeftIndent = wordApp.CentimetersToPoints(float.Parse("0")); wordApp.Selection.ParagraphFormat.RightIndent = wordApp.CentimetersToPoints(float.Parse("0")); wordApp.Selection.ClearFormatting(); wordApp.Selection.Copy(); tempDoc = tempApp.Documents.Add(); tempDoc.Paragraphs.Last.Range.Paste(); tempDoc.SaveAs(officetemp + titleHandle(pa.Range.Text.Split('\t')[0].Trim()) + ".doc", ref format, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS); tempDoc.Close(ref QS, ref QS, ref QS); } } catch { } wordApp.Selection.SetRange(end, end); progressBarX1.Value++; } } listSave(); saveDocument(); this.DialogResult = System.Windows.Forms.DialogResult.OK; this.Close(); }
private void SetPageStyle(Word.Application wordApp) { wordApp = Globals.ThisAddIn.Application; wordApp.ActiveDocument.PageSetup.TopMargin = wordApp.CentimetersToPoints(float.Parse("3.7")); wordApp.ActiveDocument.PageSetup.BottomMargin = wordApp.CentimetersToPoints(float.Parse("3.5")); wordApp.ActiveDocument.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2.8")); wordApp.ActiveDocument.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2.6")); }
public void Quality_Group() { word.Application application = new word.Application(); word.Document document = application.Documents.Add(Visible: true); word.Range range = document.Range(0, 0); string file_name = Registry_Class.DirPath + "\\УС_" + Group_name + DateTime.Now.ToString("_hh_mm_ss_dd_MM_yyyy") + ".docx"; try { document.Sections.PageSetup.LeftMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocLM)); document.Sections.PageSetup.RightMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocRM)); document.Sections.PageSetup.TopMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocTM)); document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocBM)); range.Text = Registry_Class.OrganizationName; range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; range.ParagraphFormat.SpaceAfter = 1; range.ParagraphFormat.SpaceBefore = 1; range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle; range.Font.Name = "Times New Roman"; range.Font.Size = 12; document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph Name_Doc = document.Paragraphs.Add(); Name_Doc.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; Name_Doc.Range.Font.Name = "Times New Roman"; Name_Doc.Range.Font.Size = 16; Name_Doc.Range.Text = "УСПЕВАЕМОСТЬ ГРУППЫ " + Group_name; document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph pTable = document.Paragraphs.Add(); word.Table tbQuality = document.Tables.Add(pTable.Range, 3, 2); tbQuality.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; tbQuality.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; tbQuality.Cell(1, 1).Range.Text = "Средний балл"; tbQuality.Cell(2, 1).Range.Text = "% качества"; tbQuality.Cell(3, 1).Range.Text = "% успеваемости"; tbQuality.Cell(1, 2).Range.Text = AVG; tbQuality.Cell(2, 2).Range.Text = QC; tbQuality.Cell(3, 2).Range.Text = PC; tbQuality.Range.Font.Size = 11; tbQuality.Range.Font.Name = "Times New Roman"; tbQuality.Columns[1].AutoFit(); tbQuality.Range.Paragraphs.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; } catch (Exception ex) { Registry_Class.error_message += "\n" + DateTime.Now.ToLongDateString() + " " + ex.Message; } finally { document.SaveAs2(file_name, word.WdSaveFormat.wdFormatDocumentDefault); document.Close(); application.Quit(); } }
/// <summary> /// 各种文档格式设置 /// </summary> private void PageSetup() { wordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0; //行编号 wordApp.ActiveDocument.PageSetup.Orientation = WdOrientation.wdOrientLandscape; //页面方向 wordApp.ActiveDocument.PageSetup.TopMargin = wordApp.CentimetersToPoints(float.Parse("2.54")); //上页边距 wordApp.ActiveDocument.PageSetup.BottomMargin = wordApp.CentimetersToPoints(float.Parse("2.54")); //下页边距 wordApp.ActiveDocument.PageSetup.SectionStart = WdSectionStart.wdSectionContinuous;//节的起始位置:新建页 }
public void SetPage(WOrientation orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin) { wDoc.PageSetup.PageWidth = wApp.CentimetersToPoints((float)width); wDoc.PageSetup.PageHeight = wApp.CentimetersToPoints((float)height); if (orientation == WOrientation.横板) { wDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape; } wDoc.PageSetup.TopMargin = (float)(topMargin * 25); //上边距 wDoc.PageSetup.LeftMargin = (float)(leftMargin * 25); //左边距 wDoc.PageSetup.RightMargin = (float)(rightMargin * 25); //右边距 wDoc.PageSetup.BottomMargin = (float)(bottomMargin * 25); //下边距 }
//Set the page layout, A4 sized, landscape or portrait alignment public void setPageLayout(string paper = "A4", int orient = 0) { if (orient == 0) { wordDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; } else { wordDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait; } if (paper == "A4") { wordDoc.PageSetup.PageWidth = wordApp.CentimetersToPoints(29.7F); wordDoc.PageSetup.PageHeight = wordApp.CentimetersToPoints(21F); } }
/// <summary> /// 插入图片到文档 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnClick_InsertPicture(object sender, RoutedEventArgs e) { // http://software-solutions-online.com/word-vba-insert-images/ object _start = 0; object _end = 0; Word.Range _sel = m_WordApp.ActiveDocument.Range(ref _start, ref _end); _sel.Select(); // 设置纸张方向,统一设置为横向 // TODO 需要做调整。根据图片尺寸来调整纸张方向 m_WordApp.Selection.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; // 设置页面边距 // 上下左右四个边距 m_WordApp.ActiveDocument.PageSetup.TopMargin = m_WordApp.CentimetersToPoints((float)0.25); m_WordApp.ActiveDocument.PageSetup.LeftMargin = m_WordApp.CentimetersToPoints((float)0.25); m_WordApp.ActiveDocument.PageSetup.RightMargin = m_WordApp.CentimetersToPoints((float)0.25); m_WordApp.ActiveDocument.PageSetup.BottomMargin = m_WordApp.CentimetersToPoints((float)0.25); // 遍历处理图片 if (listImages.Items.Count > 0) { foreach (var item in listImages.Items) { m_WordApp.Selection.InsertNewPage(); // 获取图片的尺寸 System.Drawing.Size imgSize = ZS.Common.Drawing.Image.GetSize(item.ToString()); if (imgSize == null) { // 做尺寸获取的错误处理 continue; } m_WordApp.Selection.InlineShapes.AddPicture(item.ToString()); } } DocumentHelper.SaveAsPDF(m_WordApp.ActiveDocument); }
public void fillHeadingSnDefault(headingSn hsn, int nIndex) { Word.Application app = Globals.ThisAddIn.Application; int i = nIndex; hsn.Index = i; hsn.NumberFormat = strsHdSnNumberFormat[i]; hsn.NumberPosition = app.CentimetersToPoints(fArrsNumberPosition[i]); hsn.TrailingCharacter = Word.WdTrailingCharacter.wdTrailingTab; hsn.NumberStyle = Word.WdListNumberStyle.wdListNumberStyleArabic; hsn.Alignment = Word.WdListLevelAlignment.wdListLevelAlignLeft; hsn.TextPosition = app.CentimetersToPoints(fArrsTextPosition[i]); hsn.TabPosition = 0.0f; hsn.ResetOnHigher = i; hsn.StartAt = 1; hsn.LinkedStyle = "标题 " + (i + 1); return; }
/*public static List<String> CompareStyles() //сравниваем эталонные стили из шаблона и стили из текущего документа * { * List<String> result = new List<string>(); * * foreach (Style style in style_from_document) //берём стиль документа * { * foreach (Style s in style_from_template) //просматриваем стили шаблона в поисках совпадающего по имени * { * if (s.StyleName.Val.Value.Equals(style.StyleName.Val.Value)) //если названия стилей совпадают * { * * if ((s.StyleParagraphProperties.SpacingBetweenLines != null) || (style.StyleParagraphProperties.SpacingBetweenLines != null) || * (!s.StyleParagraphProperties.SpacingBetweenLines.ToString().Equals(style.StyleParagraphProperties.SpacingBetweenLines.ToString()))) //расстояние между строками * result.Add("Стиль " + style.StyleName.Val.Value + " имеет расстояние между строками, отличающееся от эталонного: " + * style.StyleParagraphProperties.SpacingBetweenLines.ToString() + " вместо " + s.StyleParagraphProperties.SpacingBetweenLines.ToString()); * try * { * if ((s.StyleRunProperties.Bold != null) && (style.StyleRunProperties.Bold != null) && * (!s.StyleRunProperties.Bold.Val.Value.Equals(style.StyleRunProperties.Bold.Val.Value))) //жирное начертание * result.Add("Стиль " + style.StyleName.Val.Value + " имеет жирное начертание, отличающееся от эталонного"); * } * catch (NullReferenceException) { } * * try * { * if ((s.StyleRunProperties.Color != null) && (style.StyleRunProperties.Color != null) && * (!s.StyleRunProperties.Color.Val.Value.Equals(style.StyleRunProperties.Color.Val.Value))) //цвет текста * result.Add("Стиль " + style.StyleName.Val.Value + " имеет цвет текста, отличный от эталонного: " + * style.StyleRunProperties.Color.Val.Value + " вместо " + s.StyleRunProperties.Color.Val.Value); * } * catch (NullReferenceException) { } * * try * { * if ((s.StyleRunProperties.RunFonts != null) && (style.StyleRunProperties.RunFonts != null) && * (!s.StyleRunProperties.RunFonts.LocalName.ToString().Equals(style.StyleRunProperties.RunFonts.LocalName.ToString()))) //название шрифта * result.Add("Стиль " + style.StyleName.Val.Value + " имеет название шрифта, отличающееся от эталонного: " + * style.StyleRunProperties.RunFonts.LocalName.ToString() + " вместо " + s.StyleRunProperties.RunFonts.LocalName.ToString()); * } * catch (NullReferenceException) { } * //else result.Add("Стиль " + style.StyleName.Val.Value + " совпадает с эталонным, ура!"); * //если какого-то из свойств нет, то игнорим его * break; * } * } * } * * return result; * }*/ private static bool CheckPageMargins() { Object start = Type.Missing; Object end = Type.Missing; Word.Range wordrange = worddocument.Range(ref start, ref end); if ((wordrange.PageSetup.LeftMargin != wordapp.CentimetersToPoints((float)2.22)) && (wordrange.PageSetup.RightMargin != wordapp.CentimetersToPoints((float)1.15)) && wordrange.PageSetup.TopMargin != wordapp.CentimetersToPoints((float)2.0) && wordrange.PageSetup.BottomMargin != wordapp.CentimetersToPoints((float)2.0)) { // /*wordrange.PageSetup.LeftMargin = wordapp.CentimetersToPoints((float)2.22); * wordrange.PageSetup.RightMargin = wordapp.CentimetersToPoints((float)1.15); * wordrange.PageSetup.TopMargin = wordapp.CentimetersToPoints((float)2.0); * wordrange.PageSetup.BottomMargin = wordapp.CentimetersToPoints((float)2.0);*/ return(false); } else { return(true); } }
/// <summary> /// 初始化Word页面 /// </summary> /// <param name="wordApp">传入WordApp</param> /// <param name="wordDoc">传入WordDoc</param> private static void SetPage(MSWord.Application wordApp, MSWord.Document wordDoc) { try { wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientLandscape; wordDoc.PageSetup.TopMargin = wordApp.CentimetersToPoints(0.8f); wordDoc.PageSetup.BottomMargin = wordApp.CentimetersToPoints(0.5f); wordDoc.PageSetup.LeftMargin = wordApp.CentimetersToPoints(2.5f); wordDoc.PageSetup.RightMargin = wordApp.CentimetersToPoints(1.5f); wordDoc.PageSetup.PageHeight = wordApp.CentimetersToPoints(21); wordDoc.PageSetup.PageWidth = wordApp.CentimetersToPoints(29.7f); wordDoc.PageSetup.HeaderDistance = wordApp.CentimetersToPoints(1); wordDoc.PageSetup.FooterDistance = wordApp.CentimetersToPoints(0.5f); } catch (Exception) { ed.WriteMessage("\n设置Word页面发生未知错误,程序中断。如需帮助请联系作者。"); wordApp.Quit(ref _nothing, ref _nothing, ref _nothing); } }
public static void ExportSchedulePage(ScheduleRepository repo, string filename, bool save, bool quit, int lessonLength, int facultyId, int dayOfWeek, int daysOfWeek, bool weekFiltered, int weekFilter, bool weeksMarksVisible, bool onlyFutureDates, CancellationToken cToken) { object oMissing = Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ cToken.ThrowIfCancellationRequested(); //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); var faculty = repo.Faculties.GetFaculty(facultyId); var dow = Constants.DowLocal[dayOfWeek]; var schedule = repo.Lessons.GetFacultyDowSchedule(faculty.FacultyId, dayOfWeek, weekFiltered, weekFilter, false, onlyFutureDates); Paragraph oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Text = "Расписание"; oPara1.Range.Font.Bold = 0; oPara1.Range.Font.Size = 10; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oPara1.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); var textBoxRange = oPara1.Range; oPara1 = oDoc.Content.Paragraphs.Add(); //oPara1.Range.Text = "второго семестра 2013 – 2014 учебного года"; oPara1.Range.Text = DetectSemesterString(repo); oPara1.Range.Font.Bold = 0; oPara1.Range.Font.Size = 10; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Range.InsertParagraphAfter(); oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Text = faculty.Name; oPara1.Range.Font.Bold = 0; oPara1.Range.Font.Size = 10; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Range.InsertParagraphAfter(); oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Font.Size = 14; oPara1.Range.Text = dow.ToUpper(); oPara1.Range.Font.Bold = 1; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Range.InsertParagraphAfter(); Shape cornerStamp = oDoc.Shapes.AddTextbox( MsoTextOrientation.msoTextOrientationHorizontal, oWord.CentimetersToPoints(22f), oWord.CentimetersToPoints(0.5f), 200, 50, textBoxRange); cornerStamp.TextFrame.TextRange.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; if (dow == "Понедельник") { var prorUchRabNameOption = repo.ConfigOptions.GetFirstFiltredConfigOption(co => co.Key == "Проректор по учебной работе"); var prorUchRabName = (prorUchRabNameOption == null) ? "" : prorUchRabNameOption.Value; cornerStamp.TextFrame.TextRange.Text = @"«УТВЕРЖДАЮ»" + Environment.NewLine + "Проректор по учебной работе" + Environment.NewLine + "______________ " + prorUchRabName; cornerStamp.TextFrame.TextRange.Font.Size = 10; cornerStamp.TextFrame.TextRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; } cornerStamp.TextFrame.WordWrap = 1; cornerStamp.TextFrame.TextRange.ParagraphFormat.SpaceAfter = 0; cornerStamp.Line.Visible = MsoTriState.msoFalse; var timeList = new List<string>(); foreach (var group in schedule) { foreach (var time in group.Value.Keys) { if (!timeList.Contains(time)) { timeList.Add(time); } } } Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; cToken.ThrowIfCancellationRequested(); Table oTable = oDoc.Tables.Add(wrdRng, 1 + timeList.Count, 1 + schedule.Count); oTable.Borders.Enable = 1; oTable.Range.ParagraphFormat.SpaceAfter = 0.0F; oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oTable.Range.Font.Size = 10; oTable.Range.Font.Bold = 0; oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f); float colWidth = 25.64F / schedule.Count; for (int i = 0; i < schedule.Count; i++) { oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth); } oTable.Cell(1, 1).Range.Text = "Время"; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; int groupColumn = 2; var plainGroupsListIds = new Dictionary<int, List<int>>(); var nGroupsListIds = new Dictionary<int, List<int>>(); var plainNGroupIds = new Dictionary<int, Tuple<int, int>>(); foreach (var group in schedule) { var groupObject = repo.StudentGroups.GetStudentGroup(group.Key); var groupName = groupObject.Name; oTable.Cell(1, groupColumn).Range.Text = groupName.Replace(" (+Н)", ""); oTable.Cell(1, groupColumn).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; groupColumn++; if (groupName.Contains(" (+Н)")) { var plainGroupName = groupName.Replace(" (+Н)", ""); var nGroupName = groupName.Replace(" (+", "("); var plainGroupId = repo.StudentGroups.FindStudentGroup(plainGroupName).StudentGroupId; var plainStudentIds = repo.StudentsInGroups.GetAllStudentsInGroups() .Where(sig => sig.StudentGroup.StudentGroupId == plainGroupId) .Select(stig => stig.Student.StudentId) .ToList(); plainGroupsListIds.Add(group.Key, repo.StudentsInGroups.GetAllStudentsInGroups() .Where(sig => plainStudentIds.Contains(sig.Student.StudentId)) .Select(stig => stig.StudentGroup.StudentGroupId) .Distinct() .ToList()); var nGroupId = repo.StudentGroups.FindStudentGroup(nGroupName).StudentGroupId; var nStudentIds = repo.StudentsInGroups.GetAllStudentsInGroups() .Where(sig => sig.StudentGroup.StudentGroupId == nGroupId) .Select(stig => stig.Student.StudentId) .ToList(); nGroupsListIds.Add(group.Key, repo.StudentsInGroups.GetAllStudentsInGroups() .Where(sig => nStudentIds.Contains(sig.Student.StudentId)) .Select(stig => stig.StudentGroup.StudentGroupId) .Distinct() .ToList()); plainNGroupIds.Add(groupObject.StudentGroupId, new Tuple<int, int>(plainGroupId, nGroupId)); } } cToken.ThrowIfCancellationRequested(); var timeRowIndexList = new List<int>(); var timeRowIndex = 2; foreach (var time in timeList.OrderBy(t => int.Parse(t.Split(':')[0]) * 60 + int.Parse(t.Split(':')[1]))) { cToken.ThrowIfCancellationRequested(); var hour = int.Parse(time.Substring(0, 2)); var minute = int.Parse(time.Substring(3, 2)); minute += lessonLength; while (minute >= 60) { hour++; minute -= 60; } timeRowIndexList.Add(timeRowIndex); oTable.Cell(timeRowIndex, 1).Range.Text = time + " - " + hour.ToString("D2") + ":" + minute.ToString("D2"); oTable.Cell(timeRowIndex, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(timeRowIndex, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; var columnGroupIndex = 2; foreach (var group in schedule) { if (group.Value.ContainsKey(time)) { oTable.Cell(timeRowIndex, columnGroupIndex).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; var timeTable = oDoc.Tables.Add(oTable.Cell(timeRowIndex, columnGroupIndex).Range, 1, 1); for (int i = 0; i < group.Value[time].Count - 1; i++) { timeTable.Rows.Add(); } for (int i = 0; i < group.Value[time].Count - 1; i++) { timeTable.Cell(i + 1, 1).Borders[WdBorderType.wdBorderBottom].Visible = true; } timeTable.Range.ParagraphFormat.SpaceAfter = 0.0F; timeTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; timeTable.Range.Font.Size = 10; timeTable.Range.Font.Bold = 0; var tfdIndex = 0; foreach (var tfdData in group.Value[time].OrderBy(tfd => tfd.Value.Item2.Select(lwt => repo.CommonFunctions.CalculateWeekNumber(lwt.Item1.Calendar.Date)).Min())) { var cellText = ""; // Discipline name var primaryDisciplineName = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.Name; var names = repo.DisciplineNames.GetDisciplineNamesDictionary( tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline); if (names.ContainsKey(group.Key)) { cellText += names[group.Key]; } else { cellText += primaryDisciplineName; } // N + Group modifiers var groupId = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId; if (plainGroupsListIds.ContainsKey(group.Key)) { if (plainGroupsListIds[group.Key].Contains(groupId) && nGroupsListIds[group.Key].Contains(groupId)) { cellText += " (+Н)"; } if (!plainGroupsListIds[group.Key].Contains(groupId) && nGroupsListIds[group.Key].Contains(groupId)) { cellText += " (Н)"; } } var tfdGroupId = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId; if ((tfdGroupId != group.Key)) { if ((!plainNGroupIds.ContainsKey(group.Key)) || ((tfdGroupId != plainNGroupIds[group.Key].Item1) && (tfdGroupId != plainNGroupIds[group.Key].Item2))) { cellText += " (" + tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.Name + ")"; } } cellText += Environment.NewLine; // Teacher FIO cellText += tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Teacher.FIO + Environment.NewLine; // Total weeks if (weeksMarksVisible) { cellText += "(" + tfdData.Value.Item1 + ")" + Environment.NewLine; } var audWeekList = tfdData.Value.Item2.ToDictionary(l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date), l => l.Item1.Auditorium.Name); var grouped = audWeekList.GroupBy(a => a.Value); var enumerable = grouped as List<IGrouping<string, KeyValuePair<int, string>>> ?? grouped.ToList(); var gcount = enumerable.Count(); if (gcount == 1) { cellText += enumerable.ElementAt(0).Key; } else { for (int j = 0; j < gcount; j++) { var jItem = enumerable.OrderBy(e => e.Select(ag => ag.Key).ToList().Min()).ElementAt(j); cellText += CommonFunctions.CombineWeeks(jItem.Select(ag => ag.Key).ToList()) + " - " + jItem.Key; if (j != gcount - 1) { cellText += Environment.NewLine; } } } timeTable.Cell(tfdIndex + 1, 1).Range.Text = cellText; timeTable.Cell(tfdIndex + 1, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; tfdIndex++; } } columnGroupIndex++; } timeRowIndex++; } if (dayOfWeek == daysOfWeek) { var oPara3 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara3.Range.Font.Size = 12; oPara3.Format.LineSpacing = oWord.LinesToPoints(1); oPara3.Range.Text = ""; oPara3.Format.SpaceAfter = 0; oPara3.Range.InsertParagraphAfter(); var headUchOtdNameOption = repo.ConfigOptions.GetFirstFiltredConfigOption(co => co.Key == "Начальник учебного отдела"); var headUchOtdName = (headUchOtdNameOption == null) ? "" : headUchOtdNameOption.Value; oPara3 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara3.Range.Text = "Начальник учебного отдела\t\t" + "_________________ " + headUchOtdName; oPara3.Range.Font.Size = 12; oPara3.Range.Font.Bold = 0; oPara3.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oPara3.Format.LineSpacing = oWord.LinesToPoints(1); oPara3.Format.SpaceAfter = 0; oPara3.Range.InsertParagraphAfter(); oPara3.Range.InsertParagraphAfter(); oPara3 = oDoc.Content.Paragraphs.Add(ref oMissing); //"Декан " + UchOtd.NUDS.Core.Constants.facultyTitles[facCounter] + "\t\t_________________ " //+ UchOtd.NUDS.Core.Constants.HeadsOfFaculties.ElementAt(facCounter).Value; oPara3.Range.Text = faculty.ScheduleSigningTitle + "\t\t_________________ " + faculty.DeanSigningSchedule; oPara3.Range.Font.Size = 12; oPara3.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oPara3.Format.LineSpacing = oWord.LinesToPoints(1); oPara3.Range.Font.Bold = 0; oPara3.Format.SpaceAfter = 0; } cToken.ThrowIfCancellationRequested(); int pageCount; var fontSize = 10.5F; do { fontSize -= 0.5F; oTable.Range.Font.Size = fontSize; if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > 1); if (save) { object fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + filename; oDoc.SaveAs(ref fileName); } if (quit) { oWord.Quit(); } Marshal.ReleaseComObject(oWord); }
private void SaveAsWordDocument(int facultyFilter) { DateTime beginSessionDate, endSessionDate; DetectSessionDates(out beginSessionDate, out endSessionDate); object oMissing = Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. _Application oWord = new Application(); oWord.Visible = true; _Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); List<Faculty> faculties; if (facultyFilter != -1) { var onefaculty = _repo.Faculties.GetFaculty((int)FacultyList.SelectedValue); faculties = oneFaculty == null ? _repo.Faculties.GetAllFaculties().OrderBy(f => f.SortingOrder).ToList() : new List<Faculty> {onefaculty}; } else { faculties = _repo.Faculties.GetAllFaculties().OrderBy(f => f.SortingOrder).ToList(); } foreach (var faculty in faculties) { /* var groupIds = new List<int>(); foreach (var group in Constants.facultyGroups.ElementAt(facCounter).Value) { var groupId = _repo.FindStudentGroup(group); if (groupId != null) { groupIds.Add(groupId.StudentGroupId); } }*/ var localFaculty = faculty; var groupIds = _repo .GroupsInFaculties .GetFiltredGroupsInFaculty(gif => gif.Faculty.FacultyId == localFaculty.FacultyId) .Select(gif => gif.StudentGroup.StudentGroupId) .ToList(); var facultyExams = _repo.Exams.GetFacultyExams(_repo, groupIds); facultyExams = facultyExams .OrderBy(fe => fe.Key) .ToDictionary(keyItem => keyItem.Key, valueItem => valueItem.Value); Paragraph oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Font.Size = 24; oPara1.Format.LineSpacing = oWord.LinesToPoints(1); oPara1.Range.Text = "Расписание"; oPara1.Format.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Font.Size = 14; oPara1.Format.SpaceAfter = 0; if (beginSessionDate.Month < 3) { var startYear = beginSessionDate.Year - 1; oPara1.Range.Text = "зимней сессии " + startYear + "-" + (startYear + 1) + " учебного года" + Environment.NewLine + faculty.Name; } else { var startYear = beginSessionDate.Year - 1; oPara1.Range.Text = "летней сессии " + startYear + "-" + (startYear + 1) + " учебного года" + Environment.NewLine + faculty.Name; } oPara1.Range.InsertParagraphAfter(); Shape signBox = oDoc.Shapes .AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350, 15, 200, 75, oPara1.Range); signBox.Line.Visible = MsoTriState.msoFalse; signBox.TextFrame.ContainingRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; var prorUchRabNameOption = _repo.ConfigOptions.GetFirstFiltredConfigOption(co => co.Key == "Проректор по учебной работе"); var prorUchRabName = (prorUchRabNameOption == null) ? "" : prorUchRabNameOption.Value; signBox.TextFrame.ContainingRange.InsertAfter("«УТВЕРЖДАЮ»"); signBox.TextFrame.ContainingRange.InsertParagraphAfter(); signBox.TextFrame.ContainingRange.InsertAfter("Проректор по учебной работе"); signBox.TextFrame.ContainingRange.InsertParagraphAfter(); signBox.TextFrame.ContainingRange.InsertAfter("____________ " + prorUchRabName); Faculty local2Faculty = faculty; List<StudentGroup> groups = _repo .GroupsInFaculties .GetFiltredGroupsInFaculty(gif => gif.Faculty.FacultyId == local2Faculty.FacultyId) .Select(gif => gif.StudentGroup) .ToList(); Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Table oTable = oDoc.Tables.Add(wrdRng, 1 + facultyExams.Keys.Count, 1 + groups.Count()); //oTable.Rows(1).HeadingFormat = True; //oTable.ApplyStyleHeadingRows = True; oTable.Rows[1].HeadingFormat = -1; oTable.ApplyStyleHeadingRows = true; oTable.Borders.Enable = 1; for (int i = 1; i <= oTable.Rows.Count; i++) { oTable.Rows[i].AllowBreakAcrossPages = (int)MsoTriState.msoFalse; } oTable.Cell(1, 1).Range.Text = "Дата"; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; for (var column = 1; column <= groups.Count(); column++) { oTable.Cell(1, column + 1).Range.Text = groups[column - 1].Name; oTable.Cell(1, column + 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++) { oTable.Cell(row, 1).Range.Text = facultyExams.Keys.ElementAt(row - 2).ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU")); oTable.Cell(row, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(row, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++) { DateTime currentDate = facultyExams.Keys.ElementAt(row - 2); for (var column = 1; column <= groups.Count; column++) { if (facultyExams.ContainsKey(currentDate)) { if (facultyExams[currentDate].ContainsKey(groupIds[column - 1])) { var eventCount = facultyExams[currentDate][groupIds[column - 1]].Count; oTable.Cell(row, column + 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; var timeTable = oDoc.Tables.Add(oTable.Cell(row, column + 1).Range, 1, 1); timeTable.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow); if (eventCount > 1) { for (int i = 1; i < eventCount; i++) { timeTable.Rows.Add(); } } for (int i = 0; i < eventCount; i++) { string cellText = ""; var evt = facultyExams[currentDate][groupIds[column - 1]][i]; // Консультация || Экзамен if (evt.IsExam) { cellText += "Экзамен"; } else { cellText += "Консультация"; } cellText += Environment.NewLine; cellText += evt.DisciplineName + Environment.NewLine; cellText += evt.TeacherFio + Environment.NewLine; cellText += evt.Time.ToString("H:mm") + Environment.NewLine; cellText += evt.Auditorium; oPara1 = oDoc.Content.Paragraphs.Add(timeTable.Cell(i + 1, 1).Range); oPara1.Range.Font.Size = 10; oPara1.Format.SpaceAfter = 0; oPara1.Range.Text = cellText; if (i != eventCount - 1) { timeTable.Cell(i + 1, 1).Borders[WdBorderType.wdBorderBottom].Visible = true; } } } } } } oTable.Columns[1].Width = oWord.CentimetersToPoints(3); for (int i = 0; i < groups.Count; i++) { oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(16f / groups.Count); } oTable.Rows.Alignment = WdRowAlignment.wdAlignRowCenter; Paragraph oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = ""; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); var headUchOtdNameOption = _repo .ConfigOptions .GetFirstFiltredConfigOption(co => co.Key == "Начальник учебного отдела"); var headUchOtdName = (headUchOtdNameOption == null) ? "" : headUchOtdNameOption.Value; oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = "Начальник учебного отдела\t\t" + "_________________ " + headUchOtdName; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2.Range.InsertParagraphAfter(); oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = faculty.SessionSigningTitle + "\t\t_________________ " + faculty.DeanSigningSessionSchedule; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2.Range.InsertParagraphAfter(); if (faculty.FacultyId != faculties.OrderBy(f => f.SortingOrder).Last().FacultyId) { oDoc.Words.Last.InsertBreak(WdBreakType.wdPageBreak); } System.Windows.Forms.Application.DoEvents(); } //object fileName = Application.StartupPath + @"\Export2.docx"; //oDoc.SaveAs(ref fileName); //oWord.Quit(); }
public static void WordStartSchool(ScheduleRepository repo, string filename, bool save, bool quit, int lessonLength, int facultyId, int dayOfWeek, int daysOfWeek, bool weekFiltered, int weekFilter, bool weeksMarksVisible, CancellationToken cToken) { cToken.ThrowIfCancellationRequested(); object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); var faculty = repo.Faculties.GetFaculty(facultyId); Paragraph oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Text = "Расписание " + DetectSemesterString(repo); oPara1.Range.Font.Bold = 0; oPara1.Range.Font.Size = 10; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oPara1.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); var textBoxRange = oPara1.Range; oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Font.Size = 14; oPara1.Range.Text = Constants.DowLocal[dayOfWeek].ToUpper(); oPara1.Range.Font.Bold = 1; oPara1.Range.Font.Underline = WdUnderline.wdUnderlineSingle; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Range.InsertParagraphAfter(); Shape cornerStamp = oDoc.Shapes.AddTextbox( MsoTextOrientation.msoTextOrientationHorizontal, oWord.CentimetersToPoints(22f), oWord.CentimetersToPoints(0.5f), 200, 50, textBoxRange); cornerStamp.TextFrame.TextRange.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; if (dayOfWeek == 1) { cornerStamp.TextFrame.TextRange.Text = @"«УТВЕРЖДАЮ»" + Environment.NewLine + "Ректор ______________ Наянова М.В. «___» ____________ 20__ г."; cornerStamp.TextFrame.TextRange.Font.Size = 10; cornerStamp.TextFrame.TextRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; } cornerStamp.TextFrame.WordWrap = 1; cornerStamp.TextFrame.TextRange.ParagraphFormat.SpaceAfter = 0; cornerStamp.Line.Visible = MsoTriState.msoFalse; cToken.ThrowIfCancellationRequested(); Table oTable = GetAndPutDowStartSchedule(repo, lessonLength, dayOfWeek, weekFiltered, weekFilter, weeksMarksVisible, faculty, oDoc, oEndOfDoc, oWord, cToken); Table oTable2 = null; if ((dayOfWeek != 6) && (dayOfWeek != 7)) { oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Font.Size = 14; oPara1.Range.Text = Constants.DowLocal[dayOfWeek + 1].ToUpper(); oPara1.Range.Font.Bold = 1; oPara1.Range.Font.Underline = WdUnderline.wdUnderlineSingle; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Range.InsertParagraphAfter(); oTable2 = GetAndPutDowStartSchedule(repo, lessonLength, dayOfWeek + 1, weekFiltered, weekFilter, weeksMarksVisible, faculty, oDoc, oEndOfDoc, oWord, cToken); } cToken.ThrowIfCancellationRequested(); int pageCount; var fontSize = 10.5F; do { fontSize -= 0.5F; oTable.Range.Font.Size = fontSize; if (oTable2 != null) { oTable2.Range.Font.Size = fontSize; } if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > 1); if (save) { object fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + filename; oDoc.SaveAs(ref fileName); } if (quit) { oWord.Quit(); } Marshal.ReleaseComObject(oWord); }
public static void AuditoriumsExport(ScheduleRepository repo, Dictionary<int, Dictionary<int, List<string>>> auds, int dow, bool addTeacherFio, CancellationToken cToken) { cToken.ThrowIfCancellationRequested(); object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); /* Paragraph oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Text = Constants.DowLocal[dow]; oPara1.Range.Font.Bold = 0; oPara1.Range.Font.Size = 10; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oPara1.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); */ Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; var audIdsList = new List<int>(); foreach (var r in auds) { foreach (var a in r.Value) { if (!audIdsList.Contains(a.Key)) { audIdsList.Add(a.Key); } } } var rings = repo.Rings.GetAllRings(); var audsById = repo.Auditoriums.GetAll().ToDictionary(a => a.AuditoriumId, a => a.Name); audIdsList = audIdsList.OrderBy(id => audsById[id]).ToList(); cToken.ThrowIfCancellationRequested(); Table oTable = oDoc.Tables.Add(wrdRng, 1 + auds.Count, 1 + audIdsList.Count); oTable.Borders.Enable = 1; oTable.Range.ParagraphFormat.SpaceAfter = 0.0F; oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oTable.Range.Font.Size = 10; oTable.Range.Font.Bold = 0; oTable.Cell(1, 1).Range.Text = Constants.DowLocal[dow]; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f); float colWidth = 25.64F / audIdsList.Count; for (int i = 0; i < audIdsList.Count; i++) { oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth); oTable.Cell(1, i + 2).Range.Text = audsById[audIdsList[i]]; oTable.Cell(1, i + 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(1, i + 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; } for (int i = 0; i < auds.Count; i++) { cToken.ThrowIfCancellationRequested(); var ct = rings.First(r => r.RingId == auds.Keys.ElementAt(i)).Time.ToString("H:mm"); oTable.Cell(2 + i, 1).Range.Text = ct; oTable.Cell(2 + i, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(2 + i, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; for (int j = 0; j < audIdsList.Count; j++) { var audText = ""; if (auds[auds.Keys.ElementAt(i)].ContainsKey(audIdsList[j])) { var cnt = auds[auds.Keys.ElementAt(i)][audIdsList[j]].Count; int ii = 0; foreach (var kvp in auds[auds.Keys.ElementAt(i)][audIdsList[j]]) { if (kvp.Contains('@')) { audText += kvp.Split('@')[0]; if (addTeacherFio) { audText += " " + kvp.Substring(kvp.Split('@')[0].Length + 1); } if (ii != cnt - 1) { audText += Environment.NewLine; } } else { audText += kvp; if (ii != cnt - 1) { audText += Environment.NewLine; } } ii++; } oTable.Cell(2 + i, 2 + j).Range.Text = audText; oTable.Cell(2 + i, 2 + j).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(2 + i, 2 + j).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; } } } cToken.ThrowIfCancellationRequested(); int pageCount; var fontSize = 10.5F; do { fontSize -= 0.5F; oTable.Range.Font.Size = fontSize; if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > 1); Marshal.ReleaseComObject(oWord); }
public static void ExportCultureDates(ScheduleRepository repo) { var discs = repo.Disciplines.GetFiltredDisciplines(d => d.Name.Contains("изическ")).ToList(); discs.Sort((x, y) => { var teacherFIO1 = ""; var tfd1 = repo.TeacherForDisciplines.GetFirstFiltredTeacherForDiscipline( tefd => tefd.Discipline.DisciplineId == x.DisciplineId); if (tfd1 != null) { teacherFIO1 = tfd1.Teacher.FIO; } var teacherFIO2 = ""; var tfd2 = repo.TeacherForDisciplines.GetFirstFiltredTeacherForDiscipline( tefd => tefd.Discipline.DisciplineId == y.DisciplineId); if (tfd2 != null) { teacherFIO2 = tfd2.Teacher.FIO; } if ((teacherFIO1 == "") || (teacherFIO2 == "")) { return String.CompareOrdinal(teacherFIO1, teacherFIO2); } if (teacherFIO1 == teacherFIO2) { return tfd1.Discipline.StudentGroup.Name == tfd2.Discipline.StudentGroup.Name ? String.CompareOrdinal(tfd1.Discipline.Name, tfd2.Discipline.Name) : String.CompareOrdinal(tfd1.Discipline.StudentGroup.Name, tfd2.Discipline.StudentGroup.Name); } return String.Compare(teacherFIO1, teacherFIO2, StringComparison.Ordinal); }); object oMissing = Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); TeacherForDiscipline tfd = null; for (int i = 0; i < discs.Count; i++) { var teacherFIO = ""; tfd = repo.TeacherForDisciplines.GetFirstFiltredTeacherForDiscipline( tefd => tefd.Discipline.DisciplineId == discs[i].DisciplineId); if (tfd != null) { teacherFIO = tfd.Teacher.FIO; } Paragraph oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Text = teacherFIO + " " + discs[i].Name + " " + discs[i].PracticalHours.ToString() + " " + ((Constants.Attestation.ContainsKey(discs[i].Attestation)) ? Constants.Attestation[discs[i].Attestation] : "") + " " + discs[i].StudentGroup.Name; oPara1.Range.Font.Bold = 0; oPara1.Range.Font.Size = 10; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oPara1.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); if (tfd == null) { continue; } var tfd1 = tfd; var discLessons = repo.Lessons.GetFiltredLessons( l => l.TeacherForDiscipline.TeacherForDisciplineId == tfd1.TeacherForDisciplineId && (l.State == 1 || l.State == 2)) .ToList(); discLessons = discLessons.OrderBy(l => l.Calendar.Date).ToList(); Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Table oTable = oDoc.Tables.Add(wrdRng, discLessons.Count, 2); oTable.Borders.Enable = 1; oTable.Range.ParagraphFormat.SpaceAfter = 0.0F; oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oTable.Range.Font.Size = 14; oTable.Range.Font.Bold = 0; oTable.Columns[1].Width = oWord.CentimetersToPoints(1.2f); oTable.Columns[2].Width = oWord.CentimetersToPoints(3.25f); for (int j = 0; j < discLessons.Count; j++) { oTable.Cell(j + 1, 1).Range.Text = (j + 1).ToString(); oTable.Cell(j + 1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(j + 1, 2).Range.Text = discLessons[j].Calendar.Date.ToString("dd.MM.yyyy"); oTable.Cell(j + 1, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } var pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); var fontSize = 14.5F; do { fontSize -= 0.5F; oTable.Range.Font.Size = fontSize; if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > ((i + 1) * 2 - 1)); var endOfDoc = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; endOfDoc.Font.Size = 1; endOfDoc.InsertBreak(WdBreakType.wdSectionBreakNextPage); oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Text = teacherFIO + " " + discs[i].Name + " " + discs[i].PracticalHours.ToString() + " " + ((Constants.Attestation.ContainsKey(discs[i].Attestation)) ? Constants.Attestation[discs[i].Attestation] : "") + " " + discs[i].StudentGroup.Name; oPara1.Range.Font.Bold = 0; oPara1.Range.Font.Size = 10; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oPara1.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); var students = repo.StudentsInGroups .GetFiltredStudentsInGroups( sig => sig.StudentGroup.StudentGroupId == discs[i].StudentGroup.StudentGroupId && !sig.Student.Expelled) .Select(sig => sig.Student) .OrderBy(s => s.F) .ThenBy(s => s.I) .ThenBy(s => s.O) .ThenBy(s => s.ZachNumber) .ToList(); endOfDoc = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = endOfDoc.Tables.Add(endOfDoc, students.Count, 2); oTable.Borders.Enable = 1; oTable.Range.ParagraphFormat.SpaceAfter = 0.0F; oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oTable.Range.Font.Size = 14; oTable.Range.Font.Bold = 0; oTable.Columns[1].Width = oWord.CentimetersToPoints(1.2f); for (int j = 0; j < students.Count; j++) { var student = students[j]; oTable.Cell(j + 1, 1).Range.Text = (j + 1).ToString(); oTable.Cell(j + 1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(j + 1, 2).Range.Text = student.F + " " + student.I + " " + student.O; oTable.Cell(j + 1, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; } endOfDoc = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; endOfDoc.Font.Size = 1; endOfDoc.InsertBreak(WdBreakType.wdSectionBreakNextPage); } oDoc.Undo(); Marshal.ReleaseComObject(oWord); }
public static void TeachersSchedule(ScheduleRepository repo, TeacherSchedule tsForm, bool OnlyFutureDates, CancellationToken cToken) { var teachers = repo.Teachers.GetAllTeachers().OrderBy(t => t.FIO).ToList(); object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ int pageCounter = 0; //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); foreach (var teacher in teachers) { var result = tsForm.GetTeacherScheduleToView(teacher.TeacherId, false, -1, false, OnlyFutureDates, cToken); var isColumnEmpty = GetEmptyColumnIndexes(result); var columnTitles = new List<string>(); var columnIndexes = new List<int>(); for (int i = 1; i <= 7; i++) { if (!isColumnEmpty[i]) { columnTitles.Add(Constants.DowLocal[i]); columnIndexes.Add(i); } } Paragraph oPara1 = oDoc.Content.Paragraphs.Add(); oPara1.Range.Text = "Расписание СГОАН (" + teacher.FIO + ")"; oPara1.Range.Font.Bold = 0; oPara1.Range.Font.Size = 10; oPara1.Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oPara1.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; var dowCount = isColumnEmpty.Count(dow => !dow.Value); Table oTable = oDoc.Tables.Add(wrdRng, 1 + result.Count, 1 + dowCount); oTable.Borders.Enable = 1; oTable.Range.ParagraphFormat.SpaceAfter = 0.0F; oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oTable.Range.Font.Size = 10; oTable.Range.Font.Bold = 0; oTable.Cell(1, 1).Range.Text = "Время"; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f); float colWidth = 16.3F / dowCount; for (int i = 0; i < dowCount; i++) { oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth); oTable.Cell(1, i + 2).Range.Text = columnTitles[i]; oTable.Cell(1, i + 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } for (int i = 0; i < result.Count; i++) { oTable.Cell(2 + i, 1).Range.Text = result[i].Time; oTable.Cell(2 + i, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(2 + i, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; for (int j = 0; j < dowCount; j++) { var dowIndex = columnIndexes[j]; switch (dowIndex) { case 1: oTable.Cell(2 + i, 2 + j).Range.Text = result[i].MonLessons; break; case 2: oTable.Cell(2 + i, 2 + j).Range.Text = result[i].TueLessons; break; case 3: oTable.Cell(2 + i, 2 + j).Range.Text = result[i].WedLessons; break; case 4: oTable.Cell(2 + i, 2 + j).Range.Text = result[i].ThuLessons; break; case 5: oTable.Cell(2 + i, 2 + j).Range.Text = result[i].FriLessons; break; case 6: oTable.Cell(2 + i, 2 + j).Range.Text = result[i].SatLessons; break; case 7: oTable.Cell(2 + i, 2 + j).Range.Text = result[i].SunLessons; break; } oTable.Cell(2 + i, 2 + j).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; } } pageCounter++; int pageCount; float fontSize = 10.5F; do { fontSize -= 0.5F; oTable.Range.Font.Size = fontSize; if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > pageCounter); var endOfDoc = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; endOfDoc.Font.Size = 1; endOfDoc.InsertBreak(WdBreakType.wdSectionBreakNextPage); } oDoc.Undo(); Marshal.ReleaseComObject(oWord); }
public void Kadr_UchetWord() { word.Application application = new word.Application(); word.Document document = application.Documents.Add(Visible: true); word.Range range = document.Range(0, 0); string file_name = Registry_Class.DirPath + "\\КУ_" + DateTime.Now.ToString("_hh_mm_ss_dd_MM_yyyy") + ".docx"; try { document.Sections.PageSetup.LeftMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocLM)); document.Sections.PageSetup.RightMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocRM)); document.Sections.PageSetup.TopMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocTM)); document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocBM)); range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; range.ParagraphFormat.SpaceAfter = 1; range.ParagraphFormat.SpaceBefore = 1; range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle; range.Font.Name = "Times New Roman"; range.Font.Size = 12; document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph Name_Doc = document.Paragraphs.Add(); Name_Doc.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; Name_Doc.Range.Font.Name = "Times New Roman"; Name_Doc.Range.Font.Size = 16; Name_Doc.Range.Text = "КАДРОВЫЙ УЧЕТ"; document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph pTable = document.Paragraphs.Add(); word.Table tbCheck = document.Tables.Add(pTable.Range, table.Rows.Count + 1, table.Columns.Count); tbCheck.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; tbCheck.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; tbCheck.Cell(1, 1).Range.Text = "Код сотрудника"; tbCheck.Cell(1, 2).Range.Text = "Код табеля ЗП"; tbCheck.Cell(1, 3).Range.Text = "Код прибыли и расходов"; tbCheck.Range.Font.Size = 11; tbCheck.Range.Font.Name = "Times New Roman"; tbCheck.Columns[1].AutoFit(); for (int i = 2; i <= tbCheck.Rows.Count; i++) { for (int j = 1; j <= tbCheck.Columns.Count; j++) { tbCheck.Cell(i, j).Range.Text = table.Rows[i - 2][j - 1].ToString(); } } } catch (Exception ex) { Registry_Class.error_message += "\n" + DateTime.Now.ToLongDateString() + " " + ex.Message; } finally { document.SaveAs2(file_name, word.WdSaveFormat.wdFormatDocumentDefault); document.Close(); application.Quit(); } }
public void student_list() { word.Application application = new word.Application(); word.Document document = application.Documents.Add(Visible: true); word.Range range = document.Range(0, 0); string file_name = Registry_Class.DirPath + "\\СГ_" + Group_name + DateTime.Now.ToString("_hh_mm_ss_dd_MM_yyyy") + ".docx"; try { document.Sections.PageSetup.LeftMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocLM)); document.Sections.PageSetup.RightMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocRM)); document.Sections.PageSetup.TopMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocTM)); document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints(Convert.ToSingle(Registry_Class.DocBM)); range.Text = Registry_Class.OrganizationName; range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; range.ParagraphFormat.SpaceAfter = 1; range.ParagraphFormat.SpaceBefore = 1; range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle; range.Font.Name = "Times New Roman"; range.Font.Size = 12; document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph Name_Doc = document.Paragraphs.Add(); Name_Doc.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; Name_Doc.Range.Font.Name = "Times New Roman"; Name_Doc.Range.Font.Size = 16; Name_Doc.Range.Text = "СПИСОК ГРУППЫ " + Group_name; document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph pTable = document.Paragraphs.Add(); word.Table tbStudents = document.Tables.Add(pTable.Range, table.Rows.Count + 1, table.Columns.Count); tbStudents.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; tbStudents.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; tbStudents.Cell(1, 1).Range.Text = "№ПП"; tbStudents.Cell(1, 2).Range.Text = "Фамилия имя отчество студента"; tbStudents.Range.Font.Size = 11; tbStudents.Range.Font.Name = "Times New Roman"; tbStudents.Columns[1].AutoFit(); for (int i = 2; i <= tbStudents.Rows.Count; i++) { for (int j = 1; j <= tbStudents.Columns.Count; j++) { tbStudents.Cell(i, j).Range.Text = table.Rows[i - 2][j - 1].ToString(); } } } catch (Exception ex) { Registry_Class.error_message += "\n" + DateTime.Now.ToLongDateString() + " " + ex.Message; } finally { document.SaveAs2(file_name, word.WdSaveFormat.wdFormatDocumentDefault); document.Close(); application.Quit(); } }
public void Format_vipLS() { // Инициализация Word this.Cursor = Cursors.WaitCursor; Word.Application o_Word = new Word.Application(); Word.Document o_Doc = new Word.Document(); string d_PrintName = o_Word.ActivePrinter; string n_PrintName = comboBox1.SelectedItem.ToString(); if (chkVisible.Checked) { o_Word.Visible = false; } else { o_Word.Visible = true; } //Открытие и редактирование документа Object filename = txtFrom.Text + "\\vips.txt"; Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingOEMCyrillicII; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; if (!System.IO.File.Exists(filename.ToString())) { o_Word.Visible = true; MessageBox.Show("Файл " + filename.ToString() + " не найден.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } o_Word.Documents.Open(ref filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); o_Doc = o_Word.Documents.Application.ActiveDocument; //o_Doc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA3; o_Doc.PageSetup.PageWidth = o_Word.CentimetersToPoints(29.7f); o_Doc.PageSetup.PageHeight = o_Word.CentimetersToPoints(42f); o_Doc.PageSetup.LeftMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.RightMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.TopMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.BottomMargin = o_Word.CentimetersToPoints(1.27f); Word.Find o_Find = o_Word.Selection.Find; Word.Selection o_Sel = o_Word.Selection; o_Sel.WholeStory(); o_Sel.Font.Size = 9; o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); Object p_findText = "Нереализованная отриц."; if (o_Find.Execute(ref p_findText, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: Type.Missing, Format: false, ReplaceWith: Type.Missing, Replace: Type.Missing)) { o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdExtend); o_Sel.Delete(); o_Sel.Delete(); } else { o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); Object s_findText = "Расходы по процентам"; if (o_Find.Execute(ref s_findText, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: Type.Missing, Format: false, ReplaceWith: Type.Missing, Replace: Type.Missing)) { o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdExtend); o_Sel.Delete(); o_Sel.Delete(); } else { MessageBox.Show("Текст поиска не найден.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); o_Word.Visible = true; return;; } } //int pars = o_Doc.Paragraphs.Count;// узнаем количество строк в документе int PagesCount = o_Word.Documents.Application.ActiveDocument.Content.ComputeStatistics(Word.WdStatistic.wdStatisticPages); for (int i = 1; i <= PagesCount; i++) { o_Sel.GoTo(Word.WdGoToItem.wdGoToPage, Word.WdGoToDirection.wdGoToAbsolute, PagesCount, i); o_Sel.HomeKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.MoveRight(Unit: Type.Missing, Count: 68, Extend: Word.WdMovementType.wdMove); o_Sel.ColumnSelectMode = true; o_Sel.MoveRight(Unit: Type.Missing, Count: 85, Extend: Word.WdMovementType.wdMove); o_Sel.MoveDown(Unit: Word.WdUnits.wdLine, Count: 109, Extend: Word.WdMovementType.wdMove); o_Sel.ColumnSelectMode = false; //MessageBox.Show("Остановка"); o_Sel.Delete(); //o_Sel.HomeKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); //o_Sel.MoveDown(Unit: Word.WdUnits.wdLine, Count: 109, Extend: Type.Missing); } o_Doc.PageSetup.PageWidth = o_Word.CentimetersToPoints(21f); o_Doc.PageSetup.PageHeight = o_Word.CentimetersToPoints(29.7f); //o_Doc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4; o_Doc.PageSetup.LeftMargin = o_Word.CentimetersToPoints(2.35f); o_Word.ActivePrinter = n_PrintName; Object background = Type.Missing; Object append = Type.Missing; Object range = Type.Missing; Object outputFileName = Type.Missing; Object from = Type.Missing; Object to = Type.Missing; Object item = Type.Missing; Object copies = Type.Missing; Object pages = Type.Missing; Object pageType = Type.Missing; Object printToFile = Type.Missing; Object collate = Type.Missing; Object fileName = Type.Missing; Object activePrinterMacGX = Type.Missing; Object manualDuplexPrint = Type.Missing; Object printZoomColumn = Type.Missing; Object printZoomRow = Type.Missing; Object printZoomPaperWidth = Type.Missing; Object printZoomPaperHeight = Type.Missing; o_Doc.PrintOut(ref background, ref append, ref range, ref outputFileName, ref from, ref to, ref item, ref copies, ref pages, ref pageType, ref printToFile, ref collate, ref activePrinterMacGX, ref manualDuplexPrint, ref printZoomColumn, ref printZoomRow, ref printZoomPaperWidth, ref printZoomPaperHeight); o_Word.ActivePrinter = d_PrintName; Thread.Sleep(2000); Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ((Word._Application)o_Word).Quit(ref saveChanges, ref originalFormat, ref routeDocument); o_Word = null; this.Cursor = Cursors.Default; tSSlb.Text = "Файл " + filename + " отправлен на " + n_PrintName; }
/// <summary> /// 导出 /// </summary> /// <param name="overTimeList"></param> /// <param name="fileName"></param> public void ExportWord(List <OverTimeModel> overTimeList, string fileName) { Microsoft.Office.Interop.Word.Application app = null; Microsoft.Office.Interop.Word.Document doc = null; try { int rows = overTimeList.Count + 4; //表格行数 int cols = 6; //表格列数 object oMissing = System.Reflection.Missing.Value; object Visible = true; app = new Microsoft.Office.Interop.Word.Application(); //创建Word应用程序 doc = app.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref Visible); //添加Word文档 //设置页边距 doc.PageSetup.LeftMargin = 71; doc.PageSetup.RightMargin = 71; doc.PageSetup.TopMargin = 56.8f; doc.PageSetup.BottomMargin = 42.6f; //设置页眉页脚为1cm app.ActiveDocument.PageSetup.HeaderDistance = app.CentimetersToPoints(1f); app.ActiveDocument.PageSetup.FooterDistance = app.CentimetersToPoints(1f); //设置页眉内容 string filename = System.Windows.Forms.Application.StartupPath + "\\logo.png"; //设置图片路径 object linkToFile = false; //定义该插入的图片是否为外部链接 object saveWithDocument = true; //定义要插入的图片是否随Word文档一起保存 object headerFooterRange; //在Word中插入的位置 foreach (Section section in doc.Sections) { foreach (HeaderFooter headerFooter in section.Headers) { headerFooterRange = headerFooter.Range; //在页眉中插入 headerFooter.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; //设置图片位置为居左 doc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref headerFooterRange); //插入图片 } } //输入大标题加粗加大字号水平居中 app.Selection.Font.Bold = 700; app.Selection.Font.Size = 15; app.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; app.Selection.Text = "加班申请单"; //换行添加表格 object line = WdUnits.wdLine; app.Selection.MoveDown(ref line, oMissing, oMissing); app.Selection.TypeParagraph();//换行 Range range = app.Selection.Range; Table table = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing); table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; //设置表格的字体大小 table.Range.Font.Size = 10.5f; table.Range.Font.Bold = 0; //设置表格中的第二行为加粗 table.Rows[2].Range.Font.Bold = 700; //设置表格的行高 table.Rows.Height = 25f; table.Rows.HeightRule = WdRowHeightRule.wdRowHeightExactly; //设置表格列的宽度 table.Columns[1].Width = 75f; table.Columns[2].Width = 95f; table.Columns[3].Width = 95f; table.Columns[4].Width = 95f; table.Columns[5].Width = 70f; table.Columns[6].Width = 85f; //设置Table居中 table.Rows.Alignment = WdRowAlignment.wdAlignRowCenter; //设置第一行 int rowIndex = 1; table.Cell(rowIndex, 1).Range.Text = "申请人"; //table.Cell(rowIndex, 2).Range.Text = txtSqr.Text; this.txtSqr.Dispatcher.Invoke(new Action(() => table.Cell(rowIndex, 2).Range.Text = this.txtSqr.Text)); table.Cell(rowIndex, 3).Range.Text = "所属部门"; //table.Cell(rowIndex, 4).Range.Text = txtSsbm.Text; this.txtSsbm.Dispatcher.Invoke(new Action(() => table.Cell(rowIndex, 4).Range.Text = this.txtSsbm.Text)); table.Cell(rowIndex, 5).Range.Text = "申请时间"; //table.Cell(rowIndex, 6).Range.Text = dpSqrq.Text; this.dpSqrq.Dispatcher.Invoke(new Action(() => table.Cell(rowIndex, 6).Range.Text = this.dpSqrq.Text)); //设置第二行 rowIndex = 2; table.Cell(rowIndex, 1).Range.Text = "姓名"; table.Cell(rowIndex, 2).Range.Text = "加班类型"; table.Cell(rowIndex, 3).Range.Text = "加班时间起"; table.Cell(rowIndex, 4).Range.Text = "加班时间止"; table.Cell(rowIndex, 5).Range.Text = "小时数"; table.Cell(rowIndex, 6).Range.Text = "备注"; //循环添加数据 foreach (var i in overTimeList) { rowIndex++; table.Cell(rowIndex, 1).Range.Text = i.Name; table.Cell(rowIndex, 2).Range.Text = i.OvertimeType; table.Cell(rowIndex, 3).Range.Text = i.OvertimeStart; table.Cell(rowIndex, 4).Range.Text = i.OvertimeEnd; table.Cell(rowIndex, 5).Range.Text = i.OvertimeHours; table.Cell(rowIndex, 6).Range.Text = i.Remark; } //倒数第二行 rowIndex++; table.Cell(rowIndex, 1).Range.Text = "部门经理"; table.Cell(rowIndex, 2).Merge(table.Cell(rowIndex, 3)); table.Cell(rowIndex, 3).Range.Text = "副总经理"; table.Cell(rowIndex, 4).Merge(table.Cell(rowIndex, 5)); //倒数第一行 rowIndex++; table.Cell(rowIndex, 1).Range.Text = "常务副总经理"; table.Cell(rowIndex, 2).Merge(table.Cell(rowIndex, 3)); table.Cell(rowIndex, 3).Range.Text = "总经理"; table.Cell(rowIndex, 4).Merge(table.Cell(rowIndex, 5)); doc.SaveAs(fileName, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); MessageBox.Show("导出成功!"); this.Dispatcher.Invoke(new Action(() => this.Close())); } catch (Exception e) { MessageBox.Show(e.Message); } finally { if (doc != null) { doc.Close(); } if (app != null) { app.Quit(); } } }
private void Format_otvet() { // Инициализация Word this.Cursor = Cursors.WaitCursor; Word.Application o_Word = new Word.Application(); Word.Document o_Doc = new Word.Document(); string d_PrintName = o_Word.ActivePrinter; string n_PrintName = comboBox1.SelectedItem.ToString(); if (chkVisible.Checked) { o_Word.Visible = false; } else { o_Word.Visible = true; } //Открытие и редактирование документа Object filename = txtFrom.Text + "\\otvet.txt"; Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingOEMCyrillicII; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; if (!System.IO.File.Exists(filename.ToString())) { o_Word.Visible = true; MessageBox.Show("Файл " + filename.ToString() + " не найден.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } o_Word.Documents.Open(ref filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); //Word.Document Doc = new Word.Document(); o_Doc = o_Word.Documents.Application.ActiveDocument; o_Doc.PageSetup.LeftMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.RightMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.TopMargin = o_Word.CentimetersToPoints(1.27f); o_Doc.PageSetup.BottomMargin = o_Word.CentimetersToPoints(1.27f); Word.Find o_Find = o_Word.Selection.Find; Word.Selection o_Sel = o_Word.Selection; o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Find.Text = "ФИО: Переходченко М.В."; //Object wrap = Type.Missing; ; //Object replace = Type.Missing; ; o_Find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: Type.Missing, Format: false, ReplaceWith: Type.Missing, Replace: Type.Missing); o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Type.Missing); o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdExtend); o_Sel.Delete(); o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Find.Text = "----------------------------------------------------------------------------^p----------------------------------------------------------------------------"; o_Find.Replacement.Text = "----------------------------------------------------------------------------^m----------------------------------------------------------------------------"; Object wrap = Word.WdFindWrap.wdFindContinue; Object replace = Word.WdReplace.wdReplaceAll; o_Find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: wrap, Format: false, ReplaceWith: Type.Missing, Replace: replace); o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Word.ActivePrinter = n_PrintName; Object background = Type.Missing; Object append = Type.Missing; Object range = Type.Missing; Object outputFileName = Type.Missing; Object from = Type.Missing; Object to = Type.Missing; Object item = Type.Missing; Object copies = Type.Missing; Object pages = Type.Missing; Object pageType = Type.Missing; Object printToFile = Type.Missing; Object collate = Type.Missing; Object fileName = Type.Missing; Object activePrinterMacGX = Type.Missing; Object manualDuplexPrint = Type.Missing; Object printZoomColumn = Type.Missing; Object printZoomRow = Type.Missing; Object printZoomPaperWidth = Type.Missing; Object printZoomPaperHeight = Type.Missing; o_Doc.PrintOut(ref background, ref append, ref range, ref outputFileName, ref from, ref to, ref item, ref copies, ref pages, ref pageType, ref printToFile, ref collate, ref activePrinterMacGX, ref manualDuplexPrint, ref printZoomColumn, ref printZoomRow, ref printZoomPaperWidth, ref printZoomPaperHeight); int PagesCount = o_Word.Documents.Application.ActiveDocument.Content.ComputeStatistics(Word.WdStatistic.wdStatisticPages); o_Word.ActivePrinter = d_PrintName; Thread.Sleep(2000); Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ((Word._Application)o_Word).Quit(ref saveChanges, ref originalFormat, ref routeDocument); o_Word = null; this.Cursor = Cursors.Default; tSSlb.Text = "Файл " + filename + " отправлен на " + n_PrintName + " Всего страниц: " + PagesCount.ToString(); }
public void Format_vedLic() { // Инициализация Word this.Cursor = Cursors.WaitCursor; Word.Application o_Word = new Word.Application(); Word.Document o_Doc = new Word.Document(); if (chkVisible.Checked) { o_Word.Visible = false; } else { o_Word.Visible = true; } string dt_pick = dTPicker.Value.ToString("dd.MM.yyyy"); string dt_pick_save = dTPicker.Value.ToString("MMdd"); string[] Filelst = System.IO.Directory.GetFiles(txtFrom.Text, "day*.txt"); if (System.IO.File.Exists(Filelst.ToString())) { o_Word.Visible = true; MessageBox.Show("Файл " + Filelst.ToString() + " не найден.", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //Открытие и редактирование документа //Object o_filename = txtFrom.Text + "\\DAY"+dt_pick_save+".TXT"; Object o_filename = Filelst[0]; Object confirmConversions = Type.Missing; Object readOnly = Type.Missing; Object addToRecentFiles = Type.Missing; Object passwordDocument = Type.Missing; Object passwordTemplate = Type.Missing; Object revert = Type.Missing; Object writePasswordDocument = Type.Missing; Object writePasswordTemplate = Type.Missing; Object format = Type.Missing; Object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingOEMCyrillicII; Object visible = Type.Missing; Object openConflictDocument = Type.Missing; Object openAndRepair = Type.Missing; Object documentDirection = Type.Missing; Object noEncodingDialog = Type.Missing; o_Word.Documents.Open(ref o_filename, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref passwordTemplate, ref revert, ref writePasswordDocument, ref writePasswordTemplate, ref format, ref encoding, ref visible, ref openConflictDocument, ref openAndRepair, ref documentDirection, ref noEncodingDialog); //Редактирование документа o_Doc = o_Word.Documents.Application.ActiveDocument; o_Doc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; o_Doc.PageSetup.LeftMargin = o_Word.CentimetersToPoints(1f); o_Doc.PageSetup.RightMargin = o_Word.CentimetersToPoints(1f); o_Doc.PageSetup.TopMargin = o_Word.CentimetersToPoints(1f); o_Doc.PageSetup.BottomMargin = o_Word.CentimetersToPoints(1f); Word.Find o_Find = o_Word.Selection.Find; Word.Selection o_Sel = o_Word.Selection; o_Sel.WholeStory(); //выделяет весь текст o_Sel.Font.Size = 4; o_Sel.HomeKey(Unit: Word.WdUnits.wdStory, Extend: Word.WdMovementType.wdMove); //o_Sel.TypeText("Ведомость открытых лицевых счетов "+dt_pick+" г."+"\r\r"); o_Sel.TypeText("Ведомость открытых лицевых счетов " + dt_pick + " г."); o_Sel.TypeParagraph(); o_Sel.TypeParagraph(); o_Sel.EndKey(Unit: Word.WdUnits.wdLine, Extend: Word.WdMovementType.wdExtend); o_Sel.Delete(); //Поиск и замена o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Find.Text = "^m"; o_Find.Replacement.Text = " "; Object wrap = Word.WdFindWrap.wdFindContinue; Object replace = Word.WdReplace.wdReplaceAll; o_Find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false, MatchWildcards: false, MatchSoundsLike: Type.Missing, MatchAllWordForms: false, Forward: true, Wrap: wrap, Format: false, ReplaceWith: Type.Missing, Replace: replace); o_Find.ClearFormatting(); o_Find.Replacement.ClearFormatting(); o_Sel.EndKey(Unit: Word.WdUnits.wdStory, Extend: Type.Missing); o_Sel.TypeParagraph(); o_Sel.TypeParagraph(); o_Sel.TypeText("Руководитель ________________ Алпеева Галина Ивановна"); o_Sel.TypeParagraph(); o_Sel.TypeParagraph(); o_Sel.TypeText("Гл.бухгалтер ________________ Зотова Елена Сергеевна"); //Сохранение в формате .doc Object s_fileName = txtFrom.Text + "\\arch\\DAY" + dt_pick_save + ".doc"; Object fileformat = Word.WdSaveFormat.wdFormatDocument; o_Doc.SaveAs(ref s_fileName, ref fileformat); //Выход из Word без сохранения Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges; Object originalFormat = Type.Missing; Object routeDocument = Type.Missing; ((Word._Application)o_Word).Quit(ref saveChanges, ref originalFormat, ref routeDocument); o_Word = null; this.Cursor = Cursors.Default; tSSlb.Text = "Файл " + o_filename + " сохранен в " + s_fileName; }
/// <summary> /// Вывод полученной информации в файл Word /// </summary> /// <param name="rapporteurs"> Список, который нужно вывести </param> public static void Output(List<Rapporteur> rapporteurs) { if (rapporteurs.Count == 0) return; object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; //Start Word and create a new document. Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); Object start = Type.Missing; Object end = Type.Missing; Word.Range wordrange = oDoc.Range(ref start, ref end); //Устанавливаем поля в документе по 1,5 см wordrange.PageSetup.LeftMargin = oWord.CentimetersToPoints((float)1.5); wordrange.PageSetup.RightMargin = oWord.CentimetersToPoints((float)1.5); wordrange.PageSetup.BottomMargin = oWord.CentimetersToPoints((float)1.5); wordrange.PageSetup.TopMargin = oWord.CentimetersToPoints((float)1.5); //Insert a paragraph at the beginning of the document. Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "ПЕРЕЧЕНЬ АВТОРОВ"; Word.Range wrdRng1 = oDoc.Paragraphs[1].Range; //Форматирование документа wrdRng1.Font.Size = 14; wrdRng1.Font.Name = "Courier New"; wrdRng1.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; wrdRng1.Bold = 1; oPara1.Range.InsertParagraphAfter(); object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Word.Range wrdRng = oDoc.Paragraphs[2].Range; wrdRng.Font.Size = 12; wrdRng.Font.Name = "Courier New"; wrdRng.Bold = 0; wrdRng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; //wdAlignParagraphJustify; //Переменная, нужная для подсчета длины: длина фамилии с инициалами + длина чисел int countStr = 0; for (int i = 0; i < rapporteurs.Count; i++) { int rapporteursNumberCount = rapporteurs[i].Number.Count; wrdRng.ParagraphFormat.SpaceAfter = 6; countStr += rapporteurs[i].Name.Length; wrdRng.InsertAfter(rapporteurs[i].Name); if (rapporteursNumberCount == 1) countStr += rapporteurs[i].Number[0].Length; else { for (int k = 0; k < rapporteursNumberCount - 1; k++) countStr += rapporteurs[i].Number[k].Length + 2; countStr += rapporteurs[i].Number[rapporteursNumberCount - 1].Length; } int countP = 31 - countStr; string p = ""; for (int k = 0; k < countP; k++) p += "."; wrdRng.InsertAfter(p); for (int k = 0; k < rapporteursNumberCount - 1; k++) wrdRng.InsertAfter(rapporteurs[i].Number[k] + ", "); wrdRng.InsertAfter(rapporteurs[i].Number[rapporteurs[i].Number.Count - 1]); wrdRng.InsertParagraphAfter(); countP = 0; countStr = 0; } }
///<summary> ///Процедура формирования документа ///</summary> ///<param name="type">Тип документа</param> ///<param name="name">Название документа</param> ///<param name="table">результирующая таблица</param> public void Document_Create(Document_Type type, string name, DataTable table) { //Получение данных о документе Configuration_class configuration_Class = new Configuration_class(); configuration_Class.Document_Configuration_Get(); switch (name != "" || name != null) { case (true): switch (type) { case (Document_Type.Check): //Открытие приложения и документа в нём word.Application application = new word.Application(); word.Document document = application.Documents.Add(Visible: true); //Формирование документа try { //Начало word.Range range = document.Range(0, 0); //Поля document.Sections.PageSetup.LeftMargin = application.CentimetersToPoints((float)Configuration_class.doc_Left_Merge); document.Sections.PageSetup.RightMargin = application.CentimetersToPoints((float)Configuration_class.doc_Right_Merge); document.Sections.PageSetup.TopMargin = application.CentimetersToPoints((float)Configuration_class.doc_Top_Merge); document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge); //Присвоение текстового значения в абзац range.Text = Configuration_class.Organization_Name; //Выравнивание range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; //Интервалы в абзаце range.ParagraphFormat.SpaceAfter = 1; range.ParagraphFormat.SpaceBefore = 1; range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle; //Шрифт range.Font.Name = "Times New Roman"; range.Font.Size = 12; //Параграф (один Enter) document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); //Название документа word.Paragraph Document_Name = document.Paragraphs.Add(); //Настройка параграфа Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; Document_Name.Range.Font.Name = "Times New Roman"; Document_Name.Range.Font.Size = 16; Document_Name.Range.Text = "Выгрузка чека"; document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); //Создание таблицы word.Paragraph statparg = document.Paragraphs.Add(); word.Table stat_table = document.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count); //Настройка таблицы stat_table.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; stat_table.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; stat_table.Rows.Alignment = word.WdRowAlignment.wdAlignRowCenter; stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; stat_table.Range.Font.Size = 11; stat_table.Range.Font.Name = "Times New Roman"; //Заполнение таблицы for (int row = 1; row <= table.Rows.Count; row++) { for (int col = 1; col <= table.Columns.Count; col++) { stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString(); } } document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); //Строка даты создания word.Paragraph Footparg = document.Paragraphs.Add(); Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString()); } catch { } finally { try { //Сохранение документа document.SaveAs2(name + "DOC", word.WdSaveFormat.wdFormatDocument); //Закрытие документа document.Close(SaveChanges: false); } catch (Exception ex) { MessageBox.Show(ex.Message); } application.Quit(); } break; case (Document_Type.MarkSchemes): //Открытие приложения, создание документа (книги) и листа в нём. excel.Application application_ex = new excel.Application(); excel.Workbook workbook = application_ex.Workbooks.Add(); //excel.Worksheet worksheet = (excel.Worksheet)workbook.ActiveSheet; excel.Worksheet worksheet = workbook.ActiveSheet; try { worksheet.Name = "MarketerDoc"; worksheet.Cells[1][1] = "Отчёт о работе отдела маркетинга"; worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count + 1]].Merge(); //Заполнение таблицы for (int row = 0; row < table.Rows.Count; row++) { for (int col = 0; col < table.Columns.Count; col++) { worksheet.Cells[row + 3, col + 1] = table.Rows[row][col].ToString(); } } //Работа со стилем таблицы excel.Range border1 = worksheet.Range[worksheet.Cells[3, 1], worksheet.Cells[table.Rows.Count + 3][table.Columns.Count]]; border1.Borders.LineStyle = excel.XlLineStyle.xlContinuous; border1.VerticalAlignment = excel.XlVAlign.xlVAlignCenter; border1.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter; //Дата документа worksheet.Cells[2][table.Rows.Count + 3] = string.Format("Дата создания {0}", DateTime.Now.ToString()); //Объединение ячеек worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 3, table.Columns.Count + 2]].Merge(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { //Сохранение и выход workbook.SaveAs(name, application_ex.DefaultSaveFormat); workbook.Close(); application_ex.Quit(); } break; case (Document_Type.Order): //Открытие приложения и документа в нём word.Application application_or = new word.Application(); word.Document document_or = application_or.Documents.Add(Visible: true); //Формирование документа try { //Начало word.Range range = document_or.Range(0, 0); //Поля document_or.Sections.PageSetup.LeftMargin = application_or.CentimetersToPoints((float)Configuration_class.doc_Left_Merge); document_or.Sections.PageSetup.RightMargin = application_or.CentimetersToPoints((float)Configuration_class.doc_Right_Merge); document_or.Sections.PageSetup.TopMargin = application_or.CentimetersToPoints((float)Configuration_class.doc_Top_Merge); document_or.Sections.PageSetup.BottomMargin = application_or.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge); //Присвоение текстового значения в абзац range.Text = Configuration_class.Organization_Name; //Выравнивание range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; //Интервалы в абзаце range.ParagraphFormat.SpaceAfter = 1; range.ParagraphFormat.SpaceBefore = 1; range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle; //Шрифт range.Font.Name = "Times New Roman"; range.Font.Size = 12; //Параграф (один Enter) document_or.Paragraphs.Add(); document_or.Paragraphs.Add(); document_or.Paragraphs.Add(); //Название документа word.Paragraph Document_Name = document_or.Paragraphs.Add(); //Настройка параграфа Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; Document_Name.Range.Font.Name = "Times New Roman"; Document_Name.Range.Font.Size = 16; Document_Name.Range.Text = table.Rows[0][0].ToString(); document_or.Paragraphs.Add(); document_or.Paragraphs.Add(); document_or.Paragraphs.Add(); //Создание таблицы word.Paragraph statparg = document_or.Paragraphs.Add(); word.Paragraph Document_Text = document_or.Paragraphs.Add(); //Настройка параграфа Document_Text.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphLeft; Document_Text.Format.LeftIndent = (float)1.25; Document_Text.Range.Font.Name = "Times New Roman"; Document_Text.Range.Font.Size = 14; Document_Text.Range.Text = table.Rows[0][1].ToString(); } catch { } finally { try { //Сохранение документа document_or.SaveAs2(name + "PDF", word.WdSaveFormat.wdFormatPDF); //Закрытие документа document_or.Close(SaveChanges: false); } catch (Exception ex) { MessageBox.Show(ex.Message); } application_or.Quit(); } break; case (Document_Type.Storage): //Открытие приложения и документа в нём word.Application application_St = new word.Application(); word.Document document_St = application_St.Documents.Add(Visible: true); //Формирование документа try { //Начало word.Range range = document_St.Range(0, 0); //Поля document_St.Sections.PageSetup.LeftMargin = application_St.CentimetersToPoints((float)Configuration_class.doc_Left_Merge); document_St.Sections.PageSetup.RightMargin = application_St.CentimetersToPoints((float)Configuration_class.doc_Right_Merge); document_St.Sections.PageSetup.TopMargin = application_St.CentimetersToPoints((float)Configuration_class.doc_Top_Merge); document_St.Sections.PageSetup.BottomMargin = application_St.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge); //Присвоение текстового значения в абзац range.Text = Configuration_class.Organization_Name; //Выравнивание range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; //Интервалы в абзаце range.ParagraphFormat.SpaceAfter = 1; range.ParagraphFormat.SpaceBefore = 1; range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle; //Шрифт range.Font.Name = "Times New Roman"; range.Font.Size = 12; //Параграф (один Enter) document_St.Paragraphs.Add(); document_St.Paragraphs.Add(); document_St.Paragraphs.Add(); //Название документа word.Paragraph Document_Name = document_St.Paragraphs.Add(); //Настройка параграфа Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; Document_Name.Range.Font.Name = "Times New Roman"; Document_Name.Range.Font.Size = 16; Document_Name.Range.Text = "Выгрузка чека"; document_St.Paragraphs.Add(); document_St.Paragraphs.Add(); document_St.Paragraphs.Add(); //Создание таблицы word.Paragraph statparg = document_St.Paragraphs.Add(); word.Table stat_table = document_St.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count); //Настройка таблицы stat_table.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; stat_table.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; stat_table.Rows.Alignment = word.WdRowAlignment.wdAlignRowCenter; stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; stat_table.Range.Font.Size = 11; stat_table.Range.Font.Name = "Times New Roman"; //Заполнение таблицы for (int row = 1; row <= table.Rows.Count; row++) { for (int col = 1; col <= table.Columns.Count; col++) { stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString(); } } document_St.Paragraphs.Add(); document_St.Paragraphs.Add(); document_St.Paragraphs.Add(); //Строка даты создания word.Paragraph Footparg = document_St.Paragraphs.Add(); Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString()); } catch { } finally { try { //Сохранение документа document_St.SaveAs2(name + "DOC", word.WdSaveFormat.wdFormatDocument); //Закрытие документа document_St.Close(SaveChanges: false); } catch (Exception ex) { MessageBox.Show(ex.Message); } application_St.Quit(); } break; } break; case (false): MessageBox.Show("Введите название документа"); break; } }
/// <summary> /// 导出 /// </summary> /// <param name="overTimeList"></param> /// <param name="fileName"></param> public void ExportWord(List<OverTimeModel> overTimeList, string fileName) { Microsoft.Office.Interop.Word.Application app = null; Microsoft.Office.Interop.Word.Document doc = null; try { int rows = overTimeList.Count + 4;//表格行数 int cols = 6;//表格列数 object oMissing = System.Reflection.Missing.Value; object Visible = true; app = new Microsoft.Office.Interop.Word.Application();//创建Word应用程序 doc = app.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref Visible);//添加Word文档 //设置页边距 doc.PageSetup.LeftMargin = 71; doc.PageSetup.RightMargin = 71; doc.PageSetup.TopMargin = 56.8f; doc.PageSetup.BottomMargin = 42.6f; //设置页眉页脚为1cm app.ActiveDocument.PageSetup.HeaderDistance = app.CentimetersToPoints(1f); app.ActiveDocument.PageSetup.FooterDistance = app.CentimetersToPoints(1f); //设置页眉内容 string filename = System.Windows.Forms.Application.StartupPath + "\\logo.png";//设置图片路径 object linkToFile = false;//定义该插入的图片是否为外部链接 object saveWithDocument = true;//定义要插入的图片是否随Word文档一起保存 object headerFooterRange;//在Word中插入的位置 foreach (Section section in doc.Sections) { foreach (HeaderFooter headerFooter in section.Headers) { headerFooterRange = headerFooter.Range;//在页眉中插入 headerFooter.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//设置图片位置为居左 doc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref headerFooterRange);//插入图片 } } //输入大标题加粗加大字号水平居中 app.Selection.Font.Bold = 700; app.Selection.Font.Size = 15; app.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; app.Selection.Text = "加班申请单"; //换行添加表格 object line = WdUnits.wdLine; app.Selection.MoveDown(ref line, oMissing, oMissing); app.Selection.TypeParagraph();//换行 Range range = app.Selection.Range; Table table = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing); table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle; table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; //设置表格的字体大小 table.Range.Font.Size = 10.5f; table.Range.Font.Bold = 0; //设置表格中的第二行为加粗 table.Rows[2].Range.Font.Bold = 700; //设置表格的行高 table.Rows.Height = 25f; table.Rows.HeightRule = WdRowHeightRule.wdRowHeightExactly; //设置表格列的宽度 table.Columns[1].Width = 75f; table.Columns[2].Width = 95f; table.Columns[3].Width = 95f; table.Columns[4].Width = 95f; table.Columns[5].Width = 70f; table.Columns[6].Width = 85f; //设置Table居中 table.Rows.Alignment = WdRowAlignment.wdAlignRowCenter; //设置第一行 int rowIndex = 1; table.Cell(rowIndex, 1).Range.Text = "申请人"; //table.Cell(rowIndex, 2).Range.Text = txtSqr.Text; this.txtSqr.Dispatcher.Invoke(new Action(() => table.Cell(rowIndex, 2).Range.Text = this.txtSqr.Text)); table.Cell(rowIndex, 3).Range.Text = "所属部门"; //table.Cell(rowIndex, 4).Range.Text = txtSsbm.Text; this.txtSsbm.Dispatcher.Invoke(new Action(() => table.Cell(rowIndex, 4).Range.Text = this.txtSsbm.Text)); table.Cell(rowIndex, 5).Range.Text = "申请时间"; //table.Cell(rowIndex, 6).Range.Text = dpSqrq.Text; this.dpSqrq.Dispatcher.Invoke(new Action(() => table.Cell(rowIndex, 6).Range.Text = this.dpSqrq.Text)); //设置第二行 rowIndex = 2; table.Cell(rowIndex, 1).Range.Text = "姓名"; table.Cell(rowIndex, 2).Range.Text = "加班类型"; table.Cell(rowIndex, 3).Range.Text = "加班时间起"; table.Cell(rowIndex, 4).Range.Text = "加班时间止"; table.Cell(rowIndex, 5).Range.Text = "小时数"; table.Cell(rowIndex, 6).Range.Text = "备注"; //循环添加数据 foreach (var i in overTimeList) { rowIndex++; table.Cell(rowIndex, 1).Range.Text = i.Name; table.Cell(rowIndex, 2).Range.Text = i.OvertimeType; table.Cell(rowIndex, 3).Range.Text = i.OvertimeStart; table.Cell(rowIndex, 4).Range.Text = i.OvertimeEnd; table.Cell(rowIndex, 5).Range.Text = i.OvertimeHours; table.Cell(rowIndex, 6).Range.Text = i.Remark; } //倒数第二行 rowIndex++; table.Cell(rowIndex, 1).Range.Text = "部门经理"; table.Cell(rowIndex, 2).Merge(table.Cell(rowIndex, 3)); table.Cell(rowIndex, 3).Range.Text = "副总经理"; table.Cell(rowIndex, 4).Merge(table.Cell(rowIndex, 5)); //倒数第一行 rowIndex++; table.Cell(rowIndex, 1).Range.Text = "常务副总经理"; table.Cell(rowIndex, 2).Merge(table.Cell(rowIndex, 3)); table.Cell(rowIndex, 3).Range.Text = "总经理"; table.Cell(rowIndex, 4).Merge(table.Cell(rowIndex, 5)); doc.SaveAs(fileName, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); MessageBox.Show("导出成功!"); this.Dispatcher.Invoke(new Action(() => this.Close())); } catch (Exception e) { MessageBox.Show(e.Message); } finally { if (doc != null) { doc.Close(); } if (app != null) { app.Quit(); } } }
/// <summary> /// 插入带有编号的公式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_InsertEquation_Click(object sender, RibbonControlEventArgs e) { // 创建一个 Word Doc 变量 Word.Application app = Globals.ThisAddIn.Application; Word.Document doc = app.ActiveDocument; // 在光标处插入一个名为 equationTable 的表格 Word.Table equationTable = app.Selection.Tables.Add(app.Selection.Range, 1, 3); Range rng = equationTable.Range; // 设置 equationTable 每个单元格的具体宽度 equationTable.Cell(1, 1).SetWidth( app.CentimetersToPoints(1.75f), Word.WdRulerStyle.wdAdjustNone ); equationTable.Cell(1, 2).SetWidth( app.CentimetersToPoints(13.5f), Word.WdRulerStyle.wdAdjustNone ); equationTable.Cell(1, 3).SetWidth( app.CentimetersToPoints(1.75f), Word.WdRulerStyle.wdAdjustNone ); // 设置 equationTable 的整体边界距离为 0 equationTable.LeftPadding = 0; equationTable.RightPadding = 0; // 居中、居右 equationTable.Cell(1, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; equationTable.Cell(1, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; equationTable.Cell(1, 3).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; equationTable.Cell(1, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; equationTable.Cell(1, 3).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; // 设置段前、后的距离 rng.ParagraphFormat.LineUnitBefore = 0; rng.ParagraphFormat.LineUnitAfter = 0; rng.ParagraphFormat.SpaceBefore = 0; rng.ParagraphFormat.SpaceAfter = 0; rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceAtLeast; rng.ParagraphFormat.LineSpacing = 12; // 设置字体 equationTable.Cell(1, 1).Range.Font.NameAscii = "LM Mono 10"; equationTable.Cell(1, 2).Range.Font.NameAscii = "Latin Modern Math"; equationTable.Cell(1, 3).Range.Font.NameAscii = "LM Mono 10"; // 插入公式 app.Selection.MoveRight(Word.WdUnits.wdCell, 1); app.Selection.OMaths.Add(app.Selection.Range); // 插入域代码 app.Selection.MoveRight(Word.WdUnits.wdCell, 1); { // Type '(' app.Selection.TypeText("("); // { SEQ Chapter \c } Field chapterNumber = app.Selection.Range.Fields.Add( app.Selection.Range, Word.WdFieldType.wdFieldSequence, @"chapter \c", false ); // Type '-' app.Selection.TypeText("-"); // { SEQ Equation } Field equationNumber = app.Selection.Range.Fields.Add( app.Selection.Range, Word.WdFieldType.wdFieldSequence, @"equation", false ); // Type ')' app.Selection.TypeText(")"); } }
private int saveDocx(object filePath) { Microsoft.Office.Interop.Word.Application wrdApp; Object oMissing = System.Reflection.Missing.Value; Object oEndOfDoc = "\\endofdoc"; wrdApp = new Microsoft.Office.Interop.Word.Application(); wrdApp.Visible = false; //執行過程不在畫面上開啟 Word Microsoft.Office.Interop.Word._Document myDoc; myDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); myDoc.PageSetup.TopMargin = wrdApp.CentimetersToPoints(float.Parse("1")); myDoc.PageSetup.BottomMargin = wrdApp.CentimetersToPoints(float.Parse("1")); myDoc.PageSetup.LeftMargin = wrdApp.CentimetersToPoints(float.Parse("1")); myDoc.PageSetup.RightMargin = wrdApp.CentimetersToPoints(float.Parse("1")); Microsoft.Office.Interop.Word.Table myTable; Microsoft.Office.Interop.Word.Range wrdRng = myDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; int dataCount = dataList.Count; if (dataCount % 3 == 0) { myTable = myDoc.Tables.Add(wrdRng, dataCount, 3, ref oMissing, ref oMissing);// 新增表格 } else { dataCount = dataCount + (3 - (dataCount % 3)); myTable = myDoc.Tables.Add(wrdRng, dataCount, 3, ref oMissing, ref oMissing);// 新增表格 } myTable.Select(); wrdApp.Selection.Tables[1].Rows.Alignment = word.WdRowAlignment.wdAlignRowCenter; // 表格置中 //設定表格寬高 myTable.Rows.Height = (float)(88.4 / pixelToMm); myTable.Cell(1, 1).Column.SetWidth((float)(152.5 / pixelToMm), 0); myTable.Cell(1, 2).Column.SetWidth((float)(12.5 / pixelToMm), 0); myTable.Cell(1, 3).Column.SetWidth((float)(12.5 / pixelToMm), 0); for (int i = 0; i < dataList.Count; i++) { myTable.Range.Font.Name = "標楷體"; myTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; myTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; //設定表格內直書 myTable.Cell(i + 1, 2).Range.Orientation = word.WdTextOrientation.wdTextOrientationVerticalFarEast; myTable.Cell(i + 1, 3).Range.Orientation = word.WdTextOrientation.wdTextOrientationVerticalFarEast; if (dataList[i].dataIsEmpty == true) { continue; } //填入表格內文字 myTable.Cell(i + 1, 2).Range.Text = dataList[i].des; myTable.Cell(i + 1, 3).Range.Text = dataList[i].title; //剪貼簿複製圖片過去 if (dataList[i].imageData == null) { continue; } Microsoft.Office.Interop.Word.Range a = myDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Clipboard.SetImage(dataList[i].imageData); myTable.Cell(i + 1, 1).Range.InsertParagraphAfter(); myTable.Cell(i + 1, 1).Range.Select(); myTable.Cell(i + 1, 1).Range.Paste(); //設定表格置中 myTable.Cell(i + 1, 1).VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; myTable.Cell(i + 1, 1).Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; } Object oFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument; //格式 myDoc.SaveAs(ref filePath, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); Object oFalse = false; myDoc.Close(ref oFalse, ref oMissing, ref oMissing); return 1; }
public static void ExportTypeSequenceInfoByFaculty(ScheduleRepository repo) { var faculties = repo.Faculties.GetAllFaculties().OrderBy(f => f.SortingOrder).ToList(); object oMissing = Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); for (int i = 0; i < faculties.Count; i++) { var faculty = faculties[i]; AddPara(oDoc, faculty.Name, 14); var facultyGroups = repo.GroupsInFaculties .GetFiltredGroupsInFaculty(gif => gif.Faculty.FacultyId == faculty.FacultyId) .Select(gif => gif.StudentGroup) .ToList(); for (int j = 0; j < facultyGroups.Count; j++) { var studentGroup = facultyGroups[j]; AddPara(oDoc, studentGroup.Name); var studentIds = repo .StudentsInGroups .GetFiltredStudentsInGroups(sig => sig.StudentGroup.StudentGroupId == studentGroup.StudentGroupId && !sig.Student.Expelled) .ToList() .Select(stig => stig.Student.StudentId); var groupsListIds = repo .StudentsInGroups .GetFiltredStudentsInGroups(sig => studentIds.Contains(sig.Student.StudentId)) .ToList() .Select(stig => stig.StudentGroup.StudentGroupId) .Distinct() .ToList(); var groupDisciplines = repo.Disciplines.GetFiltredDisciplines( d => groupsListIds.Contains(d.StudentGroup.StudentGroupId)).ToList(); Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Table oTable = oDoc.Tables.Add(wrdRng, groupDisciplines.Count+1, 2); oTable.Borders.Enable = 1; oTable.Range.ParagraphFormat.SpaceAfter = 0.0F; oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oTable.Range.Font.Size = 14; oTable.Range.Font.Bold = 0; oTable.Cell(1, 1).Range.Text = "Дисциплина"; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(1, 2).Range.Text = "Последовательность занятий"; oTable.Cell(1, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; for (int k = 0; k < groupDisciplines.Count; k++) { var discipline = groupDisciplines[k]; oTable.Cell(k + 2, 1).Range.Text = discipline.Name; oTable.Cell(k + 2, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; var sequence = (discipline.AuditoriumHours != 0 && string.IsNullOrEmpty(discipline.TypeSequence)) ? "Нет данных" : discipline.TypeSequence; oTable.Cell(k + 2, 2).Range.Text = sequence; oTable.Cell(k + 2, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; } } AddPara(oDoc, "", 1); Range wordRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Table legendTable = oDoc.Tables.Add(wordRng, 1 + Constants.LessonTypeLongAbbreviation.Count, 2); legendTable.Borders.Enable = 1; legendTable.Cell(1, 1).Range.Text = "Код"; legendTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; legendTable.Cell(1, 2).Range.Text = "Вид занятия"; legendTable.Cell(1, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; var lineNumber = 2; foreach (var kvp in Constants.LessonTypeLongAbbreviation.OrderBy(p => p.Key)) { legendTable.Cell(lineNumber, 1).Range.Text = kvp.Key.ToString(); legendTable.Cell(lineNumber, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; legendTable.Cell(lineNumber, 2).Range.Text = kvp.Value; legendTable.Cell(lineNumber, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; lineNumber++; } AddPara(oDoc, "", 1); var wordRng2 = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Table signTable = oDoc.Tables.Add(wordRng2, 1, 2); signTable.Borders.Enable = 0; signTable.Range.Bold = 0; signTable.Cell(1, 1).Range.Text = faculty.ScheduleSigningTitle; signTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; signTable.Cell(1, 2).Range.Text = "_________________ " + faculty.DeanSigningSchedule; signTable.Cell(1, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; var endOfDoc = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; endOfDoc.Font.Size = 1; endOfDoc.InsertBreak(WdBreakType.wdSectionBreakNextPage); } oDoc.Undo(); Marshal.ReleaseComObject(oWord); }
private void OpetionWord(ApiModuleDTO apiModule) { try { #region //写入普通文本 string t1 = "标题 1"; string t2 = "标题 2"; string t3 = "标题 3"; string body = "正文"; strContent = "标题一\n"; if (!apiModule.ApiTag.Equals(Tag)) { Tag = apiModule.ApiTag; wordDoc.Paragraphs.Last.Range.set_Style(t1); wordDoc.Paragraphs.Last.Range.Text = apiModule.ApiTagDec + "\n"; } wordDoc.Paragraphs.Last.Range.set_Style(t2); wordDoc.Paragraphs.Last.Range.Text = apiModule.ApiName + "\n"; #endregion #region wordDoc.Paragraphs.Last.Range.set_Style(body); int tableColumn = 4; int tableRow = 7; wordApp.Selection.EndKey(ref unite, ref Nothing); MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing); table.Borders.Enable = 1; table.Columns[1].Width = 120; table.Columns[2].Width = 50; table.Columns[3].Width = 70; table.Columns[4].Width = 150; table.Cell(1, 1).Merge(table.Cell(1, 4)); table.Cell(2, 2).Merge(table.Cell(2, 4)); table.Cell(3, 2).Merge(table.Cell(3, 4)); table.Cell(4, 2).Merge(table.Cell(4, 4)); table.Cell(5, 2).Merge(table.Cell(5, 4)); table.Cell(1, 1).Range.Text = "接口信息"; table.Cell(2, 1).Range.Text = dic.Keys.ToList()[0]; table.Cell(3, 1).Range.Text = dic.Keys.ToList()[1]; table.Cell(4, 1).Range.Text = dic.Keys.ToList()[2]; table.Cell(5, 1).Range.Text = dic.Keys.ToList()[3]; table.Cell(2, 2).Range.Text = apiModule.ApiUrl; table.Cell(3, 2).Range.Text = apiModule.DataFormat; table.Cell(4, 2).Range.Text = apiModule.ApiWay; table.Cell(5, 2).Range.Text = apiModule.ApiExplain; table.Cell(6, 1).Merge(table.Cell(6, 4)); table.Cell(6, 1).Range.Text = "输入参数"; int col = 1; int iniNum = 0; foreach (var item in dic.Keys) { table.Cell(7, col).Range.Text = item; table.Cell(7, col).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; col++; } iniNum = tableRow; var addCount = apiModule.ApiParame.Count; if (addCount > 0) { iniNum += 1; } for (int i = 0; i < apiModule.ApiParame.Count; i++) { table.Rows.Add(ref Nothing); table.Rows[iniNum + i].Height = 17; table.Rows[iniNum + i].Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft; table.Cell(iniNum + i, 1).Range.Text = apiModule.ApiParame[i].Name; table.Cell(iniNum + i, 2).Range.Text = apiModule.ApiParame[i].Schema.type; table.Cell(iniNum + i, 3).Range.Text = apiModule.ApiParame[i].Schema.nullable ? "必填" : string.Empty; table.Cell(iniNum + i, 4).Range.Text = apiModule.ApiParame[i].Schema.description; } iniNum = tableRow + addCount; if (apiModule.IsRequestBody) { iniNum = iniNum + 1; } var paramNum = 0; if (apiModule.IsRequestBody) { paramNum = iniNum; table.Rows.Add(ref Nothing); table.Rows[iniNum].Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft; table.Cell(iniNum, 1).Range.Text = apiModule.ApiParameFormet; } iniNum = iniNum + 1; var resultTagNum = iniNum; table.Rows.Add(ref Nothing); table.Rows[iniNum].Height = 17; table.Cell(iniNum, 1).Range.Text = "输出参数"; iniNum = iniNum + 1; var resultNum = iniNum; table.Rows.Add(ref Nothing); table.Rows[iniNum].Height = 17; table.Rows[iniNum].Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; table.Cell(iniNum, 1).Range.Text = dic.Keys.ToList()[0]; table.Cell(iniNum, 2).Range.Text = dic.Keys.ToList()[1]; table.Cell(iniNum, 3).Range.Text = dic.Keys.ToList()[3]; table.Rows.Add(ref Nothing); table.Rows[iniNum].Height = 17; var addResultValueCount = apiModule.Components != null ? apiModule.Components.properties.Keys.Count : 0; iniNum = iniNum + 1; for (int i = 0; i < addResultValueCount; i++) { var key = apiModule.Components.properties.ToList()[i].Key; var format = string.IsNullOrEmpty(apiModule.Components.properties[key].format) ? apiModule.Components.properties[key].type : apiModule.Components.properties[key].format; var desc = apiModule.Components.properties[key].items != null ? "见附录:" + apiModule.ComponentSubDescription + string.Format("({0})", apiModule.Components.properties[key].items.RefPath.Substring(apiModule.Components.properties[key].items.RefPath.LastIndexOf("/") + 1)) : apiModule.Components.properties[key].description; table.Rows.Add(ref Nothing); table.Rows[iniNum + i].Height = 17; table.Rows[iniNum + i].Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft; table.Cell(iniNum + i, 1).Range.Text = key; table.Cell(iniNum + i, 2).Range.Text = format; table.Cell(iniNum + i, 3).Range.Text = desc; table.Cell(iniNum + i, 3).Merge(table.Cell(iniNum + i, 4)); } if (paramNum > 0) { table.Cell(paramNum, 1).Merge(table.Cell(paramNum, 4)); } table.Cell(resultTagNum, 1).Merge(table.Cell(resultTagNum, 4)); table.Cell(resultTagNum, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft; table.Cell(resultNum, 3).Merge(table.Cell(resultNum, 4)); iniNum = iniNum + addResultValueCount; table.Cell(iniNum, 2).Merge(table.Cell(iniNum, 4)); table.Cell(iniNum, 1).Range.Text = apiModule.ResultCode.Keys.ToList().Count > 0 ? apiModule.ResultCode.Keys.ToList()[0] : string.Empty; table.Cell(iniNum, 2).Range.Text = apiModule.ResultCode.Keys.ToList().Count > 0 ? apiModule.ResultCode.Values.ToList()[0].description : string.Empty; table.Rows.Add(ref Nothing); table.Rows[iniNum].Height = 17; iniNum = iniNum + 1; table.Cell(iniNum, 1).Merge(table.Cell(iniNum, 2)); table.Cell(iniNum, 1).Range.Text = apiModule.ResultCode.Values.ToList().Count > 0 ? apiModule.ResultCode.Values.ToList()[0].content : string.Empty; table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast; table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8")); table.Range.Font.Size = 10.5F; table.Range.Font.Bold = 0; table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter; table.Rows[1].Range.Font.Bold = 1;//加粗 table.Rows[1].Range.Font.Size = 12F; table.Cell(1, 1).Range.Font.Size = 10.5F; wordApp.Selection.Cells.Height = 30;//所有单元格的高度 wordApp.Selection.EndKey(ref unite, ref Nothing); #endregion } catch (Exception ex) { throw ex; } }
public static void ExportWholeScheduleOneGroupPerPage(ScheduleRepository repo, MainEditForm form, CancellationToken cToken) { cToken.ThrowIfCancellationRequested(); //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ int pageCounter = 0; foreach (var faculty in repo.Faculties.GetAllFaculties()) { //var faculty = repo.GetFirstFiltredFaculty(f => f.SortingOrder == i); var facultyGroups = repo.Faculties.GetFacultyGroups(faculty.FacultyId); foreach (var group in facultyGroups) { cToken.ThrowIfCancellationRequested(); var sStarts = repo.CommonFunctions.GetSemesterStarts(); var groupLessons = repo.Lessons.GetGroupedGroupLessons(group.StudentGroupId, sStarts, -1, false, false); var groupEvents = form.CreateGroupTableView(group.StudentGroupId, groupLessons, false); Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Table oTable = oDoc.Tables.Add(wrdRng, 1 + groupEvents.Count, 7); oTable.Borders.Enable = 1; oTable.Range.ParagraphFormat.SpaceAfter = 0.0F; oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oTable.Range.Font.Size = 10; oTable.Range.Font.Bold = 0; oTable.Cell(1, 1).Range.Text = group.Name; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f); const float colWidth = 25.64F / 6; for (int j = 1; j <= 6; j++) { oTable.Columns[j + 1].Width = oWord.CentimetersToPoints(colWidth); oTable.Cell(1, j + 1).Range.Text = Constants.DowLocal[j]; oTable.Cell(1, j + 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } for (int j = 0; j < groupEvents.Count; j++) { cToken.ThrowIfCancellationRequested(); oTable.Cell(j + 2, 1).Range.Text = groupEvents[j].Time; oTable.Cell(j + 2, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(j + 2, 2).Range.Text = groupEvents[j].MonEvents; oTable.Cell(j + 2, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 3).Range.Text = groupEvents[j].TueEvents; oTable.Cell(j + 2, 3).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 4).Range.Text = groupEvents[j].WenEvents; oTable.Cell(j + 2, 4).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 5).Range.Text = groupEvents[j].ThuEvents; oTable.Cell(j + 2, 5).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 6).Range.Text = groupEvents[j].FriEvents; oTable.Cell(j + 2, 6).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 7).Range.Text = groupEvents[j].SatEvents; oTable.Cell(j + 2, 7).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; } pageCounter++; int pageCount; float fontSize = 10.5F; do { fontSize -= 0.5F; oTable.Range.Font.Size = fontSize; if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > pageCounter); var endOfDoc = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; endOfDoc.Font.Size = 1; endOfDoc.InsertBreak(WdBreakType.wdSectionBreakNextPage); } } }
public void Document_Create(Document_Type type, Document_Format format, string name, DataTable table) { Configuration_class configuration_Class = new Configuration_class(); configuration_Class.Document_Configuration_Get(); switch (name != "" || name != null) { case true: switch (format) { case Document_Format.Word: word.Application application = new word.Application(); word.Document document = application.Documents.Add(Visible: true); try { word.Range range = document.Range(0, 0); document.Sections.PageSetup.LeftMargin = application.CentimetersToPoints((float)Configuration_class.doc_Left_Merge); document.Sections.PageSetup.RightMargin = application.CentimetersToPoints((float)Configuration_class.doc_Right_Merge); document.Sections.PageSetup.TopMargin = application.CentimetersToPoints((float)Configuration_class.doc_Top_Merge); document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints((float)Configuration_class.doc_Bottom_Merge); range.Text = Configuration_class.Organiztion_Name; range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; range.ParagraphFormat.SpaceAfter = 1; range.ParagraphFormat.SpaceBefore = 1; range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle; range.Font.Name = "Times New Roman"; range.Font.Size = 12; document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph Document_Name = document.Paragraphs.Add(); Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; Document_Name.Range.Font.Name = "Times New Roman"; Document_Name.Range.Font.Size = 16; switch (type) { case Document_Type.Report: Document_Name.Range.Text = "ОТЧЁТ"; break; case Document_Type Statistic: Document_Name.Range.Text = "СТАТИСТИЧЕСКИЙ ОТЧЁТ"; break; } document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph statparg = document.Paragraphs.Add(); word.Table stat_table = document.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count); stat_table.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; stat_table.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; stat_table.Rows.Alignment = word.WdRowAlignment.wdAlignRowCenter; stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; stat_table.Range.Font.Size = 12; stat_table.Range.Font.Name = "Times New Roman"; for (int row = 1; row <= table.Rows.Count; row++) { for (int col = 1; col <= table.Columns.Count; col++) { stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString(); } } document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph Footparg = document.Paragraphs.Add(); Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString("dd.MM.yyyy")); } catch { } finally { switch (format) { case Document_Format.Word: document.SaveAs2(name, word.WdSaveFormat.wdFormatDocument); break; case Document_Format.PDF: document.SaveAs2(name, word.WdSaveFormat.wdFormatPDF); break; } document.Close(); application.Quit(); } break; case Document_Format.Excel: excel.Application application_ex = new excel.Application(); excel.Workbook workbook = application_ex.Workbooks.Add(); excel.Worksheet worksheet = (excel.Worksheet)workbook.ActiveSheet(); try { switch (type) { case Document_Type.Report: worksheet.Name = "Отчет"; for (int row = 0; row < table.Rows.Count; row++) { for (int col = 0; col < table.Columns.Count; col++) { worksheet.Cells[row + 1][col + 1] = table.Rows[row][col].ToString(); } } excel.Range border = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[worksheet.Rows.Count + 1][table.Columns.Count + 1]]; border.Borders.LineStyle = excel.XlLineStyle.xlContinuous; border.VerticalAlignment = excel.XlHAlign.xlHAlignCenter; border.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter; worksheet.Cells[table.Rows.Count + 3][2] = string.Format("Дата создания {0}", DateTime.Now.ToString()); worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 2]].Merge(); break; case Document_Type.Statistic: worksheet.Name = "Статистический отчет"; for (int row = 0; row < table.Rows.Count; row++) { for (int col = 0; col < table.Columns.Count; col++) { worksheet.Cells[row + 1][col + 1] = table.Rows[row][col].ToString(); } } excel.Range border1 = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[worksheet.Rows.Count + 1][table.Columns.Count + 1]]; border1.Borders.LineStyle = excel.XlLineStyle.xlContinuous; border1.VerticalAlignment = excel.XlHAlign.xlHAlignCenter; border1.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter; worksheet.Cells[table.Rows.Count + 3][2] = string.Format("Дата создания {0}", DateTime.Now.ToString()); excel.ChartObjects chartObjects = (excel.ChartObjects)worksheet.ChartObjects(Type.Missing); excel.ChartObject chartObject = chartObjects.Add(300, 50, 250, 250); excel.Chart chart = chartObject.Chart; excel.SeriesCollection seriesCollection = (excel.SeriesCollection)chart.SeriesCollection(Type.Missing); excel.Series series = seriesCollection.NewSeries(); chart.ChartType = excel.XlChartType.xl3DColumn; series.XValues = worksheet.get_Range("B2", "B" + table.Rows.Count + 1); series.Values = worksheet.get_Range("C2", "C" + table.Rows.Count + 1); break; } } catch { } finally { workbook.SaveAs(name, application_ex.DefaultSaveFormat); workbook.Close(); application_ex.Quit(); } break; } break; case false: System.Windows.Forms.MessageBox.Show("Введите название документа"); break; } }
public static void WordSchoolTwoDays(ScheduleRepository repo, string filename, bool save, bool quit, int lessonLength, int facultyId, int dayOfWeek, int daysOfWeek, bool weekFiltered, int weekFilter, bool weeksMarksVisible, CancellationToken cToken) { object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); var faculty = repo.Faculties.GetFaculty(facultyId); var oTable = GetAndPutDowSchedule(repo, lessonLength, dayOfWeek, weekFiltered, weekFilter, weeksMarksVisible, faculty, oDoc, oEndOfDoc, oWord, null, cToken); if (dayOfWeek != 7) { oTable = GetAndPutDowSchedule(repo, lessonLength, dayOfWeek + 1, weekFiltered, weekFilter, weeksMarksVisible, faculty, oDoc, oEndOfDoc, oWord, oTable, cToken); } int pageCount; var fontSize = 10.5F; do { fontSize -= 0.5F; oTable.Range.Font.Size = fontSize; if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > 1); if (save) { object fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + filename; oDoc.SaveAs(ref fileName); } if (quit) { oWord.Quit(); } Marshal.ReleaseComObject(oWord); }
protected void Button1_Click(object sender, EventArgs e) { object Nothing = System.Reflection.Missing.Value;//定义一个missing wordApp = new Msword.ApplicationClass();//对wordapp进行初始化 wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);//对一个wordDoc进行初始化 object filename = "F:\\aa.doc"; if (File.Exists(filename.ToString()))//判断文件是否存在 { File.Delete(filename.ToString());//若文件存在就删除这个文件 } wordApp.Visible = false;//设置动态建立的word文档可见 wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2"));//设置word文档的左边距 wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));//设置word文档右边距 wordApp.ActiveWindow.HorizontalPercentScrolled = 11;//设置文档的水平滑动距离 wordApp.ActiveWindow.View.Type = Msword.WdViewType.wdOutlineView;//设置文档的页眉类型 wordApp.ActiveWindow.View.SeekView = Msword.WdSeekView.wdSeekCurrentPageHeader;//设置文档的页眉是显示在文档的头部 wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("这是我的页眉内容"); wordApp.Selection.ParagraphFormat.Alignment = Msword.WdParagraphAlignment.wdAlignParagraphRight;//设置页眉内容的对齐方式 //wordApp.ActiveWindow.View.SeekView = Msword.WdSeekView.wdSeekMainDocument;//跳出页眉设置 wordApp.Selection.ParagraphFormat.LineSpacing = 11f;//设置段落的距离为11f Msword.Paragraph para1;//定义一个段落为para1 para1 = wordDoc.Paragraphs.Add(ref Nothing);//对para1进行初始化 para1.Range.Text = "这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2";//对段落para1进行添加内容 para1.Format.CharacterUnitFirstLineIndent = 2;//设置首行缩进 para1.Range.Font.Color = Msword.WdColor.wdColorBlue;//设置字体的颜色 para1.Format.SpaceAfter = 6;//在段落para1后面设置空行为6 para1.Range.InsertParagraphAfter();//将段落para1添加到文档中 Msword.Paragraph para2;//同上 object endofdoc = "\\endofdoc";//定义标签endofdoc,"endofdoc"表示文档的末尾书签 object range1 = wordDoc.Bookmarks.get_Item(ref endofdoc).Range;//定位到文档的书签处 para2 = wordDoc.Paragraphs.Add(ref range1);//同上 para2.Range.Text = "asfdasdfasdfasdffasdfsadfasdfasfdasdfas";//同上 para2.Range.InsertParagraphAfter();//同上 Msword.Paragraph para3;//同上 object range2 = wordDoc.Bookmarks.get_Item(ref endofdoc).Range;//同上 para3 = wordDoc.Paragraphs.Add(ref range2);//同上 para3.Range.Text = "eeeeeeeeeeeeeeeeeeeeeeee";//同上 object sttar = (object)(para3.Range.Start + 2);//"para3.Range.Start "表示para3段落的开始处加上两个字符 object eend = (object)(para3.Range.Start + 2);//同上 wordDoc.Range(ref sttar, ref eend).InsertBefore("ttt");//定位到para3段落的开始处加上两个字符并添加内容"ttt" para3.Format.CharacterUnitFirstLineIndent = 2;//设置首行缩进 para3.Range.Font.Bold = 5;//设置段落para3字体颜色 para3.Range.InsertParagraphAfter();//同上 Msword.Table table1 = wordDoc.Tables.Add(para3.Range, 8, 8, ref Nothing, ref Nothing);//在文档中添加8行8列的表格 table1.Cell(1, 1).Range.Font.Color = Msword.WdColor.wdColorBrown;//设置表格中的第1行1列的字体颜色为wdColorBrown table1.Cell(1, 1).Range.Text = "搜点的撒旦";//在表格中的第一行第一类中添加内容 table1.Range.ParagraphFormat.Alignment = Msword.WdParagraphAlignment.wdAlignParagraphRight;//设置表格中的内容alignment table1.Cell(3, 3).Merge(table1.Cell(8, 3));//将3行3列一直到8行3列进行组合成一列 object row = 4; object col = 4; table1.Cell(3, 1).Split(ref row, ref col);//将3行1列分开为4行4列 string picturefile = "D:\\ly\\应用\\test.jpg";//设置图片的路径 object linktofile = false; object linktodoctument = true; object x1 = (object)(para2.Range.Start); object x2 = (object)(para2.Range.End); object rr1 = wordDoc.Range(ref x1, ref x2); wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(picturefile, ref linktofile, ref linktodoctument, ref rr1);//将图片添加到文档中 //将图片的外形设置为可变 Msword.Shape shape1 = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); shape1.WrapFormat.Type = Msword.WdWrapType.wdWrapSquare; //保存wordDoc wordDoc.SaveAs(ref filename, 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, ref Nothing); //释放内存 wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); }
internal static void ExportTwoDaysInPageFacultySchedule( ScheduleRepository repo, string filename, bool save, bool quit, int lessonLength, int facultyId, int daysOfWeek, bool weekFiltered, int weekFilter, bool weeksMarksVisible) { object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); int currentPageNum = 1; var faculty = repo.Faculties.GetFaculty(facultyId); for (int dayOfWeek = 1; dayOfWeek <= 5; dayOfWeek += 2) { var firstDaySchedule = repo.Lessons.GetFacultyDowSchedule(faculty.FacultyId, dayOfWeek, weekFiltered, weekFilter, false, false); var firstDayTable = PutDayScheduleInWord(repo, lessonLength, weeksMarksVisible, firstDaySchedule, oDoc, oEndOfDoc, oWord, null, dayOfWeek); var secondDaySchedule = repo.Lessons.GetFacultyDowSchedule(faculty.FacultyId, dayOfWeek + 1, weekFiltered, weekFilter, false, false); var secondDayTable = PutDayScheduleInWord(repo, lessonLength, weeksMarksVisible, secondDaySchedule, oDoc, oEndOfDoc, oWord, firstDayTable, dayOfWeek + 1); var fontSize = 10.5F; int pageCount; do { fontSize -= 0.5F; firstDayTable.Range.Font.Size = fontSize; if (secondDayTable != null) { secondDayTable.Range.Font.Size = fontSize; } if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > currentPageNum); var endOfDoc = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; endOfDoc.Font.Size = 1; endOfDoc.InsertBreak(WdBreakType.wdSectionBreakNextPage); currentPageNum++; } oDoc.Undo(); if (save) { object fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + filename; oDoc.SaveAs(ref fileName); } if (quit) { oWord.Quit(); } Marshal.ReleaseComObject(oWord); }
private void SaveAsWordDocument() { DateTime beginSessionDate, endSessionDate; DetectSessionDates(out beginSessionDate, out endSessionDate); object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. Word._Application oWord = new Word.Application(); oWord.Visible = true; Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); var faculties = _sRepo.GetAllFaculties(); for (int facCounter = 0; facCounter < Constants.Constants.facultyGroups.Keys.Count; facCounter++) { var groupIds = new List <int>(); foreach (var group in Constants.Constants.facultyGroups.ElementAt(facCounter).Value) { var groupId = _sRepo.FindStudentGroup(group); if (groupId != null) { groupIds.Add(groupId.StudentGroupId); } } var facultyExams = _repo.GetFacultyExams(_sRepo, groupIds); facultyExams = facultyExams.OrderBy(fe => fe.Key).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value); Word.Paragraph oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Font.Size = 24; oPara1.Format.LineSpacing = oWord.LinesToPoints(1); oPara1.Range.Text = "Расписание"; oPara1.Format.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Font.Size = 14; oPara1.Format.SpaceAfter = 0; if (beginSessionDate.Month < 3) { var startYear = beginSessionDate.Year - 1; oPara1.Range.Text = "зимней сессии " + startYear + "-" + (startYear + 1) + " учебного года" + Environment.NewLine + Constants.Constants.facultyTitles[facCounter]; } else { var startYear = beginSessionDate.Year - 1; oPara1.Range.Text = "летней сессии " + startYear + "-" + (startYear + 1) + " учебного года" + Environment.NewLine + Constants.Constants.facultyTitles[facCounter]; } oPara1.Range.InsertParagraphAfter(); Word.Shape signBox = oDoc.Shapes .AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350, 15, 200, 75, oPara1.Range); signBox.Line.Visible = MsoTriState.msoFalse; signBox.TextFrame.ContainingRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; signBox.TextFrame.ContainingRange.InsertAfter("«УТВЕРЖДАЮ»"); signBox.TextFrame.ContainingRange.InsertParagraphAfter(); signBox.TextFrame.ContainingRange.InsertAfter("Проректор по учебной работе"); signBox.TextFrame.ContainingRange.InsertParagraphAfter(); signBox.TextFrame.ContainingRange.InsertAfter("____________ А.В. Синицкий"); var groups = Constants.Constants.facultyGroups.ElementAt(facCounter).Value; Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 1 + facultyExams.Keys.Count, 1 + groups.Count); //oTable.Rows(1).HeadingFormat = True; //oTable.ApplyStyleHeadingRows = True; oTable.Rows[1].HeadingFormat = -1; oTable.ApplyStyleHeadingRows = true; oTable.Borders.Enable = 1; for (int i = 1; i <= oTable.Rows.Count; i++) { oTable.Rows[i].AllowBreakAcrossPages = (int)Microsoft.Office.Core.MsoTriState.msoFalse; } oTable.Cell(1, 1).Range.Text = "Дата"; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; for (var column = 1; column <= groups.Count; column++) { oTable.Cell(1, column + 1).Range.Text = groups[column - 1]; oTable.Cell(1, column + 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++) { oTable.Cell(row, 1).Range.Text = facultyExams.Keys.ElementAt(row - 2).ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU")); oTable.Cell(row, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(row, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } DateTime currentDate; for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++) { currentDate = facultyExams.Keys.ElementAt(row - 2); for (var column = 1; column <= groups.Count; column++) { if (facultyExams.ContainsKey(currentDate)) { if (facultyExams[currentDate].ContainsKey(groupIds[column - 1])) { var eventCount = facultyExams[currentDate][groupIds[column - 1]].Count; oTable.Cell(row, column + 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; var timeTable = oDoc.Tables.Add(oTable.Cell(row, column + 1).Range, 1, 1); timeTable.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow); if (eventCount > 1) { for (int i = 1; i < eventCount; i++) { timeTable.Rows.Add(); } } for (int i = 0; i < eventCount; i++) { string cellText = ""; var evt = facultyExams[currentDate][groupIds[column - 1]][i]; // Консультация || Экзамен if (evt.IsExam) { cellText += "Экзамен"; } else { cellText += "Консультация"; } cellText += Environment.NewLine; cellText += evt.DisciplineName + Environment.NewLine; cellText += evt.TeacherFIO + Environment.NewLine; cellText += evt.Time.ToString("H:mm") + Environment.NewLine; cellText += evt.Auditorium; oPara1 = oDoc.Content.Paragraphs.Add(timeTable.Cell(i + 1, 1).Range); oPara1.Range.Font.Size = 10; oPara1.Format.SpaceAfter = 0; oPara1.Range.Text = cellText; if (i != eventCount - 1) { timeTable.Cell(i + 1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = true; } } } } } } oTable.Columns[1].Width = oWord.CentimetersToPoints(3); for (int i = 0; i < groups.Count; i++) { oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(16 / groups.Count); } oTable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter; Word.Paragraph oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = ""; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = "Начальник учебного отдела\t\t" + "_________________ " + Constants.Constants.UchOtdHead; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2.Range.InsertParagraphAfter(); oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = "Декан " + Constants.Constants.facultyTitles[facCounter] + "\t\t_________________ " + Constants.Constants.HeadsOfFaculties.ElementAt(facCounter).Value; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2.Range.InsertParagraphAfter(); if (facCounter != Constants.Constants.facultyGroups.Keys.Count - 1) { oDoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak); } Application.DoEvents(); } object fileName = Application.StartupPath + @"\Export2.docx"; //oDoc.SaveAs(ref fileName); //oWord.Quit(); }
public static void ExportGroupSchedulePage(ScheduleRepository repo, MainEditForm form, int groupId, bool weekFilteredF, int weekFilterNum, bool onlyFutureDates, CancellationToken cToken) { cToken.ThrowIfCancellationRequested(); //Start Word and create a new document. _Application oWord = new Application { Visible = true }; _Document oDoc = oWord.Documents.Add(); oDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape; oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ var group = repo.StudentGroups.GetStudentGroup(groupId); var sStarts = repo.CommonFunctions.GetSemesterStarts(); cToken.ThrowIfCancellationRequested(); var weekFilter = -1; if (weekFilteredF) { weekFilter = weekFilterNum; } var groupLessons = repo.Lessons.GetGroupedGroupLessons(group.StudentGroupId, sStarts, weekFilter, false, onlyFutureDates); cToken.ThrowIfCancellationRequested(); List<GroupTableView> groupEvents = form.CreateGroupTableView(group.StudentGroupId, groupLessons, false); Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Table oTable = oDoc.Tables.Add(wrdRng, 1 + groupEvents.Count, 7); oTable.Borders.Enable = 1; oTable.Range.ParagraphFormat.SpaceAfter = 0.0F; oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; oTable.Range.Font.Size = 10; oTable.Range.Font.Bold = 0; oTable.Cell(1, 1).Range.Text = group.Name; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f); const float colWidth = 25.64F / 6; for (int j = 1; j <= 6; j++) { oTable.Columns[j + 1].Width = oWord.CentimetersToPoints(colWidth); oTable.Cell(1, j + 1).Range.Text = Constants.DowLocal[j]; oTable.Cell(1, j + 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } for (int j = 0; j < groupEvents.Count; j++) { cToken.ThrowIfCancellationRequested(); oTable.Cell(j + 2, 1).Range.Text = groupEvents[j].Time; oTable.Cell(j + 2, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; oTable.Cell(j + 2, 2).Range.Text = groupEvents[j].MonEvents; oTable.Cell(j + 2, 2).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 3).Range.Text = groupEvents[j].TueEvents; oTable.Cell(j + 2, 3).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 4).Range.Text = groupEvents[j].WenEvents; oTable.Cell(j + 2, 4).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 5).Range.Text = groupEvents[j].ThuEvents; oTable.Cell(j + 2, 5).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 6).Range.Text = groupEvents[j].FriEvents; oTable.Cell(j + 2, 6).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(j + 2, 7).Range.Text = groupEvents[j].SatEvents; oTable.Cell(j + 2, 7).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; } cToken.ThrowIfCancellationRequested(); int pageCount; float fontSize = 10.5F; do { fontSize -= 0.5F; oTable.Range.Font.Size = fontSize; if (fontSize <= 3) { break; } pageCount = oDoc.ComputeStatistics(WdStatistic.wdStatisticPages); } while (pageCount > 1); }
public static void Create(string Whom, string LRaport, string[] TextRaport, string Date, string Position, string Rank, string Name1) { Word.Application application = new Word.Application(); //Создаём объект приложения ворд Word.Document doc = new Word.Document(); //Создаём объект документа try //Обработчик ошибок { doc = application.Documents.Add(); //Создаём текстовый документ } catch (Exception Error) { doc.Close(); application.Quit(); doc = null; application = null; throw Error; } doc.Content.Font.Name = "Times New Roman"; //Шрифт для всего документа doc.Content.Font.Size = 14; //размер шрифта для документа Word.Paragraphs docParagraphs; Word.Paragraph docParagraph; docParagraphs = doc.Paragraphs; docParagraphs.Add(); //создание нового абзаца docParagraph = docParagraphs[1]; docParagraph.Range.Text = Whom; //Первый абзац документа docParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; //Выравнивание первого абзаца по правой стороне docParagraphs.Add(); docParagraphs.Add(); docParagraphs.Add(); docParagraphs.Add(); docParagraphs.Add(); docParagraph = docParagraphs[5]; int paragraph = 5; string t = LRaport; //Присваивание значения переменной docParagraph.Range.Text = t; //присваивание значения абзацу №5 docParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //выравнивание абзаца №5 по центру foreach (string text in TextRaport) { paragraph++; docParagraphs.Add(); docParagraph = docParagraphs[paragraph]; docParagraph.Range.ParagraphFormat.FirstLineIndent = application.CentimetersToPoints((float)1.25); //отступ 1.25 string stTxt = text; docParagraph.Range.Text = stTxt; docParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; // выравнивание абзаца по ширине } docParagraphs.Add(); paragraph++; //Разрыв раздела и добавление колонок object units = Word.WdUnits.wdStory; object extend = Word.WdMovementType.wdMove; application.Selection.EndKey(ref units, ref extend); //перевод курсора в конец документа docParagraph = docParagraphs[paragraph]; docParagraph.Range.ParagraphFormat.FirstLineIndent = 0; object oType = Word.WdBreakType.wdSectionBreakContinuous; //разрыв раздела на текущей странице application.Selection.InsertBreak(oType); application.Selection.PageSetup.TextColumns.SetCount(2); //создание 2 колонок в разделе paragraph++; docParagraphs.Add(); docParagraph = docParagraphs[paragraph]; docParagraph.Range.Text = Date + " г."; docParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; paragraph++; docParagraphs.Add(); paragraph++; docParagraphs.Add(); docParagraph = docParagraphs[paragraph]; docParagraph.Range.Text = Position; docParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; paragraph++; docParagraphs.Add(); docParagraph = docParagraphs[paragraph]; docParagraph.Range.Text = Rank + "\t\t\t" + Name1; docParagraph.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //Новый разрыв раздела и замена 2 колонок на 1 units = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; application.Selection.EndKey(ref units, ref extend); oType = Word.WdBreakType.wdSectionBreakContinuous; application.Selection.InsertBreak(oType); application.Selection.PageSetup.TextColumns.SetCount(1); application.Visible = true; //Ворд видим }
private int saveDocx(object filePath) { Microsoft.Office.Interop.Word.Application wrdApp; Object oMissing = System.Reflection.Missing.Value; Object oEndOfDoc = "\\endofdoc"; wrdApp = new Microsoft.Office.Interop.Word.Application(); wrdApp.Visible = false; //執行過程不在畫面上開啟 Word Microsoft.Office.Interop.Word._Document myDoc; myDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); myDoc.PageSetup.TopMargin = wrdApp.CentimetersToPoints(float.Parse("1")); myDoc.PageSetup.BottomMargin = wrdApp.CentimetersToPoints(float.Parse("1")); myDoc.PageSetup.LeftMargin = wrdApp.CentimetersToPoints(float.Parse("1")); myDoc.PageSetup.RightMargin = wrdApp.CentimetersToPoints(float.Parse("1")); Microsoft.Office.Interop.Word.Table myTable; Microsoft.Office.Interop.Word.Range wrdRng = myDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; int dataCount = dataList.Count; if (dataCount % 3 == 0) { myTable = myDoc.Tables.Add(wrdRng, dataCount, 3, ref oMissing, ref oMissing);// 新增表格 } else { dataCount = dataCount + (3 - (dataCount % 3)); myTable = myDoc.Tables.Add(wrdRng, dataCount, 3, ref oMissing, ref oMissing);// 新增表格 } myTable.Select(); wrdApp.Selection.Tables[1].Rows.Alignment = word.WdRowAlignment.wdAlignRowCenter; // 表格置中 //設定表格寬高 myTable.Rows.Height = (float)(88.4 / pixelToMm); myTable.Cell(1, 1).Column.SetWidth((float)(152.5 / pixelToMm), 0); myTable.Cell(1, 2).Column.SetWidth((float)(12.5 / pixelToMm), 0); myTable.Cell(1, 3).Column.SetWidth((float)(12.5 / pixelToMm), 0); for (int i = 0; i < dataList.Count; i++) { myTable.Range.Font.Name = "標楷體"; myTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; myTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; //設定表格內直書 myTable.Cell(i + 1, 2).Range.Orientation = word.WdTextOrientation.wdTextOrientationVerticalFarEast; myTable.Cell(i + 1, 3).Range.Orientation = word.WdTextOrientation.wdTextOrientationVerticalFarEast; if (dataList[i].dataIsEmpty == true) { continue; } //填入表格內文字 myTable.Cell(i + 1, 2).Range.Text = dataList[i].des; myTable.Cell(i + 1, 3).Range.Text = dataList[i].title; //剪貼簿複製圖片過去 if (dataList[i].imageData == null) { continue; } Microsoft.Office.Interop.Word.Range a = myDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; Clipboard.SetImage(dataList[i].imageData); myTable.Cell(i + 1, 1).Range.InsertParagraphAfter(); myTable.Cell(i + 1, 1).Range.Select(); myTable.Cell(i + 1, 1).Range.Paste(); //設定表格置中 myTable.Cell(i + 1, 1).VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; myTable.Cell(i + 1, 1).Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; } Object oFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument; //格式 myDoc.SaveAs(ref filePath, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); Object oFalse = false; myDoc.Close(ref oFalse, ref oMissing, ref oMissing); return(1); }
/// <summary> /// 将剪贴板中的内容放入表格,自动生成行号 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_InsertCodeBox_Click(object sender, RibbonControlEventArgs e) { // 创建一个 Word Doc 变量 Word.Application app = Globals.ThisAddIn.Application; Word.Document doc = app.ActiveDocument; // 在光标处插入一个名为 CodeTable 的表格 Word.Table codeTable = app.Selection.Tables.Add(app.Selection.Range, 1, 2); // 打开代码单元格的表格边界 codeTable.Cell(1, 2).Borders.Enable = 1; // 设置单元格宽度 codeTable.Cell(1, 1).SetWidth(app.CentimetersToPoints(0.75f), Word.WdRulerStyle.wdAdjustNone); codeTable.Cell(1, 2).SetWidth(app.CentimetersToPoints(16.25f), Word.WdRulerStyle.wdAdjustNone); // 整体边界填充 codeTable.LeftPadding = app.CentimetersToPoints(0.1f); codeTable.RightPadding = app.CentimetersToPoints(0.1f); // 设置段前、后的距离 codeTable.Range.ParagraphFormat.LineUnitBefore = 0; codeTable.Range.ParagraphFormat.LineUnitAfter = 0; codeTable.Range.ParagraphFormat.SpaceBefore = 0; codeTable.Range.ParagraphFormat.SpaceAfter = 0; // 设置行距 codeTable.Range.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly; codeTable.Range.ParagraphFormat.LineSpacing = 12; // 设置字体 codeTable.Range.Font.NameAscii = dropDown_CodeFont_ASCII.SelectedItem.ToString(); codeTable.Range.Font.NameFarEast = dropDown_CodeFont_FarEast.SelectedItem.ToString(); codeTable.Range.Font.Size = 9; // 设置单元格对齐方式 codeTable.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; codeTable.Cell(1, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; // 中英文字符间距自动调整:Disable codeTable.Cell(1, 2).Range.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 0; codeTable.Cell(1, 2).Range.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 0; // 计算行号 string tmp_clipboard = Clipboard.GetText(); string[] AllLines = tmp_clipboard.Split('\n'); int numberOfLines = AllLines.Length; // 打印连续的行号,最大步长 maxStep 从下拉菜单中选择,默认为 1 int maxStep = Int32.Parse(dropDown_lineStep.SelectedItem.ToString()); // int maxCharsOfEachLine = 97; // LM Mono 10, 9pt, 16.5cm int maxCharsOfEachLine = 102; // Iosevka, 9pt, 16.5cm int numOfPrint = numberOfLines / maxStep; { string totalLines = ""; if (maxStep == 1) { int numOfLineBreaks = 0; for (int i = 1; i <= numberOfLines - 1; i++) { int remainder = AllLines[i - 1].Length % maxCharsOfEachLine; int isRemainderExist = 0; if (remainder == 0) { isRemainderExist = 0; } else { isRemainderExist = 1; } numOfLineBreaks = AllLines[i - 1].Length / maxCharsOfEachLine + isRemainderExist; totalLines = totalLines + i.ToString(); for (int j = 0; j < numOfLineBreaks; j++) { totalLines = totalLines + "\n"; } } totalLines = totalLines + numberOfLines.ToString(); } else { // 先存储 1 和 maxStep - 1 个换行符 totalLines = totalLines + 1.ToString(); for (int i = 1; i <= (maxStep - 1); i++) { totalLines = totalLines + "\n"; } // 打印 maxStep 开始的整数组字符 for (int i = 1; i <= numOfPrint - 1; i++) { totalLines = totalLines + (i * maxStep).ToString(); for (int j = 1; j <= maxStep; j++) { totalLines = totalLines + "\n"; } } totalLines = totalLines + (numOfPrint * maxStep).ToString(); // 打印最后的零散空格 int numOfRemainder = numberOfLines % maxStep; for (int i = 1; i <= (numOfRemainder); i++) { totalLines = totalLines + "\n"; } } app.Selection.TypeText(totalLines); } // 将剪贴板中的 HTML 代码贴入 app.Selection.MoveRight(Word.WdUnits.wdCell, 1); app.Selection.Range.Paste(); // 调整代码单元格的内容 codeTable.Cell(1, 2).Range.Font.NameAscii = dropDown_CodeFont_ASCII.SelectedItem.ToString(); codeTable.Cell(1, 2).Range.Font.NameFarEast = dropDown_CodeFont_FarEast.SelectedItem.ToString(); codeTable.Cell(1, 2).Range.Font.Size = 9; codeTable.Cell(1, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; codeTable.Cell(1, 2).Range.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 0; codeTable.Cell(1, 2).Range.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 0; codeTable.Cell(1, 2).Range.ParagraphFormat.CharacterUnitFirstLineIndent = 0; codeTable.Cell(1, 2).Range.ParagraphFormat.CharacterUnitLeftIndent = 0; codeTable.Cell(1, 2).Range.ParagraphFormat.CharacterUnitRightIndent = 0; codeTable.Cell(1, 2).Range.ParagraphFormat.FirstLineIndent = app.CentimetersToPoints(0); codeTable.Cell(1, 2).Range.ParagraphFormat.FarEastLineBreakControl = 0; codeTable.Range.ParagraphFormat.LineUnitBefore = 0; codeTable.Range.ParagraphFormat.LineUnitAfter = 0; codeTable.Range.ParagraphFormat.SpaceBefore = 0; codeTable.Range.ParagraphFormat.SpaceAfter = 0; codeTable.Range.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly; codeTable.Range.ParagraphFormat.LineSpacing = 12; codeTable.Range.Font.Bold = 0; codeTable.Range.ParagraphFormat.WordWrap = 0; }
public static void ExportWordData(DataTable wordData, DataTable textData, DataTable classTable, DateTime PeriodDateFrom, DateTime PeriodDateTo, DataTable CHLDReport) { try { _Word._Application WordApp = new _Word.Application(); _Word._Document WordDoc = new _Word.Document(); object oMissing = Missing.Value; object oEndOfDoc = "\\endofdoc"; WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); _Word.Paragraph oPara1; oPara1 = WordDoc.Content.Paragraphs.Add(ref oMissing); if (PeriodDateFrom.ToString("MMMMyyyy") == PeriodDateTo.ToString("MMMMyyyy")) { oPara1.Range.Text = $"Информация о детях, обратившихся за медицинской помощью в медицинские организации Краснодарского края из оздоровительных организаций всех форм собственности Краснодарского края за {PeriodDateTo:MMMM yyyy}"; } else if (PeriodDateFrom.ToString("yyyy") == PeriodDateTo.ToString("yyyy")) { oPara1.Range.Text = $"Информация о детях, обратившихся за медицинской помощью в медицинские организации Краснодарского края из оздоровительных организаций всех форм собственности Краснодарского края за {PeriodDateFrom:MMMM}-{PeriodDateTo:MMMM yyyy}"; } else { oPara1.Range.Text = $"Информация о детях, обратившихся за медицинской помощью в медицинские организации Краснодарского края из оздоровительных организаций всех форм собственности Краснодарского края за {PeriodDateFrom:MMMM yyyy}-{PeriodDateTo:MMMM yyyy}"; } oPara1.Range.Font.Bold = 1; oPara1.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara1.Range.Font.Name = "Times New Roman"; oPara1.Range.Font.Size = 14; //Размер шрифта абзаца oPara1.Format.SpaceAfter = 14; oPara1.Range.InsertParagraphAfter(); _Word.Table oTable; _Word.Range wrdRng = WordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = WordDoc.Tables.Add(wrdRng, 3 + wordData.Rows.Count, 10, ref oMissing, ref oMissing); // Размерность таблицы Nх10 (N - кол-во строк зависит от кол-ва строк в принимаемом аргументе, 10 столбцов) oTable.AutoFitBehavior(_Word.WdAutoFitBehavior.wdAutoFitFixed); // wdAutoFitFixed - фиксированный размер столбцов oTable.Rows.SetLeftIndent(-65, _Word.WdRulerStyle.wdAdjustNone); //Смещение таблицы влево на 75 единиц oTable.Range.ParagraphFormat.SpaceBefore = 6; oTable.Range.Bold = 0; //Выделение шрифта жирным oTable.Range.Font.Size = 10; //Размер шрифта в таблице oTable.Range.ParagraphFormat.SpaceAfter = 14; oTable.Range.ParagraphFormat.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphCenter; //Горизонтальное выравнивание текста по центру ячейки oTable.Range.Cells.VerticalAlignment = _Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //Вертикальное выравнивание текста в ячейке oTable.Borders.InsideLineStyle = _Word.WdLineStyle.wdLineStyleSingle; //Отрисовка сплошных линий внутри таблицы oTable.Borders.OutsideLineStyle = _Word.WdLineStyle.wdLineStyleSingle; //Отрисовка сплошных линий снаружи таблицы //Размеры столбцов в единицах oTable.Columns[1].Width = 90; //102 oTable.Columns[2].Width = 67; oTable.Columns[3].Width = 40; oTable.Columns[4].Width = 40; oTable.Columns[5].Width = 40; oTable.Columns[6].Width = 40; oTable.Columns[7].Width = 60.03f; oTable.Columns[8].Width = 62.64f; oTable.Columns[9].Width = 63.51f; oTable.Columns[10].Width = 63; //66.41f; oTable.Rows[2].Height = 85; //Высота 2 строки в таблице oTable.Rows[1].Cells[1].Range.Text = "Территория"; oTable.Rows[1].Cells[2].Range.Text = "Количество случаев"; oTable.Rows[1].Cells[3].Range.Text = "Ребёнок находится на организованном отдыхе"; oTable.Rows[2].Cells[3].Range.Text = "Самостоятельно"; oTable.Rows[2].Cells[4].Range.Text = "По путевке Мать и дитя"; oTable.Rows[1].Cells[5].Range.Text = "Ребёнок находится на неорганизованном отдыхе"; oTable.Rows[2].Cells[5].Range.Text = "Самостоятельно"; oTable.Rows[2].Cells[6].Range.Text = "С законным представителем"; oTable.Rows[1].Cells[7].Range.Text = "Первичная медико-санитарная помощь (ПМСП)"; oTable.Rows[1].Cells[8].Range.Text = "Первичная специализированная медико-санитарная помощь (ПСМСП)"; oTable.Rows[1].Cells[9].Range.Text = "Специализированная медицинская помощь (СМП)"; oTable.Rows[1].Cells[10].Range.Text = "Направлен (переведён) в реанимацию"; oTable.Cell(1, 1).Merge(oTable.Cell(2, 1)); //Объединение 1 ячейки 1 строки с 1 ячейкой 2 строки oTable.Cell(1, 2).Merge(oTable.Cell(2, 2)); //Объединение 2 ячейки 1 строки со 2 ячейкой 2 строки oTable.Cell(1, 3).Merge(oTable.Cell(1, 4)); //Объединение 3 ячейки 1 строки с 4 ячейкой 1 строки oTable.Cell(1, 4).Merge(oTable.Cell(1, 5)); //Объединение 4 ячейки 1 строки с 5 ячейкой 1 строки oTable.Cell(1, 5).Merge(oTable.Cell(2, 7)); //Объединение 5 ячейки 1 строки с 7 ячейкой 2 строки oTable.Cell(1, 6).Merge(oTable.Cell(2, 8)); //Объединение 6 ячейки 1 строки с 8 ячейкой 2 строки oTable.Cell(1, 7).Merge(oTable.Cell(2, 9)); //Объединение 7 ячейки 1 строки с 9 ячейкой 2 строки oTable.Cell(1, 8).Merge(oTable.Cell(2, 10)); //Объединение 8 ячейки 1 строки с 10 ячейкой 2 строки oTable.Cell(2, 3).Range.Orientation = _Word.WdTextOrientation.wdTextOrientationUpward; //Направление текста вверх на 90 градусов oTable.Cell(2, 4).Range.Orientation = _Word.WdTextOrientation.wdTextOrientationUpward; //Направление текста вверх на 90 градусов oTable.Cell(2, 5).Range.Orientation = _Word.WdTextOrientation.wdTextOrientationUpward; //Направление текста вверх на 90 градусов oTable.Cell(2, 6).Range.Orientation = _Word.WdTextOrientation.wdTextOrientationUpward; //Направление текста вверх на 90 градусов for (int i = 0; i < wordData.Rows.Count; i++) { for (int j = 0; j < 10; j++) { oTable.Cell(i + 3, j + 1).Range.Text = wordData.Rows[i][j].ToString(); } } oTable.Cell(3 + wordData.Rows.Count, 1).Range.Bold = 1; oTable.Cell(3 + wordData.Rows.Count, 1).Range.Text = "Итого"; for (int j = 2; j <= 10; j++) { int sumColumn = 0; for (int i = 3; i < oTable.Rows.Count; i++) { string _char = oTable.Cell(i, j).Range.Text.ToString(); _char = _char.Remove(_char.Length - 2, 2); sumColumn += int.Parse(_char); } oTable.Cell(3 + wordData.Rows.Count, j).Range.Bold = 1; oTable.Cell(3 + wordData.Rows.Count, j).Range.Text = sumColumn.ToString(); } _Word.Paragraph oPara3; oPara3 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara3.Range.Font.Bold = 0; oPara3.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara3.Range.Font.Name = "Times New Roman"; oPara3.Range.Font.Size = 14; //Размер шрифта абзаца oPara3.Format.SpaceAfter = 14; string itog = oTable.Cell(oTable.Rows.Count, 2).Range.Text.ToString(); itog = itog.Remove(itog.Length - 2, 2); if (PeriodDateFrom.ToString("MMMMyyyy") == PeriodDateTo.ToString("MMMMyyyy")) { oPara3.Range.Text = $"За {PeriodDateTo:MMMM yyyy} за медицинской помощью обратились {itog} детей, из них:"; } else if (PeriodDateFrom.ToString("yyyy") == PeriodDateTo.ToString("yyyy")) { oPara3.Range.Text = $"За {PeriodDateFrom:MMMM}-{PeriodDateTo:MMMM yyyy} за медицинской помощью обратились {itog} детей, из них:"; } else { oPara3.Range.Text = $"За {PeriodDateFrom:MMMM yyyy}-{PeriodDateTo:MMMM yyyy} за медицинской помощью обратились {itog} детей, из них:"; } oPara3.Range.InsertParagraphAfter(); string area = ""; string relax = ""; string doo = ""; string help = ""; string diag = ""; //Создание многоуровнего списка(в данном случае создается 5 уровней) _Word.ListTemplate template = WordApp.ListGalleries[_Word.WdListGalleryType.wdOutlineNumberGallery].ListTemplates.get_Item(1); //1-й уровень _Word.ListLevel level = template.ListLevels[1]; level.NumberFormat = "%1."; level.TrailingCharacter = _Word.WdTrailingCharacter.wdTrailingTab; level.NumberStyle = _Word.WdListNumberStyle.wdListNumberStyleArabic; level.NumberPosition = WordApp.CentimetersToPoints(0f); level.Alignment = _Word.WdListLevelAlignment.wdListLevelAlignLeft; level.TextPosition = WordApp.CentimetersToPoints(0.63f); level.TabPosition = (float)_Word.WdConstants.wdUndefined; level.ResetOnHigher = 0; level.StartAt = 1; level.Font.Bold = 0; level.Font.Italic = (int)_Word.WdConstants.wdUndefined; level.Font.StrikeThrough = (int)_Word.WdConstants.wdUndefined; level.Font.Subscript = (int)_Word.WdConstants.wdUndefined; level.Font.Superscript = (int)_Word.WdConstants.wdUndefined; level.Font.Shadow = (int)_Word.WdConstants.wdUndefined; level.Font.Outline = (int)_Word.WdConstants.wdUndefined; level.Font.Emboss = (int)_Word.WdConstants.wdUndefined; level.Font.Engrave = (int)_Word.WdConstants.wdUndefined; level.Font.AllCaps = (int)_Word.WdConstants.wdUndefined; level.Font.Hidden = (int)_Word.WdConstants.wdUndefined; level.Font.Underline = _Word.WdUnderline.wdUnderlineNone; level.Font.Color = _Word.WdColor.wdColorAutomatic; level.Font.Size = (int)_Word.WdConstants.wdUndefined; level.Font.Animation = _Word.WdAnimation.wdAnimationNone; level.Font.DoubleStrikeThrough = (int)_Word.WdConstants.wdUndefined; level.LinkedStyle = ""; //2-й уровень level = template.ListLevels[2]; level.NumberFormat = "%1.%2."; level.TrailingCharacter = _Word.WdTrailingCharacter.wdTrailingTab; level.NumberStyle = _Word.WdListNumberStyle.wdListNumberStyleArabic; level.NumberPosition = WordApp.CentimetersToPoints(0.63f); level.Alignment = _Word.WdListLevelAlignment.wdListLevelAlignLeft; level.TextPosition = WordApp.CentimetersToPoints(1.4f); level.TabPosition = (float)_Word.WdConstants.wdUndefined; level.ResetOnHigher = 1; level.StartAt = 1; level.Font.Bold = 0; level.Font.Italic = (int)_Word.WdConstants.wdUndefined; level.Font.StrikeThrough = (int)_Word.WdConstants.wdUndefined; level.Font.Subscript = (int)_Word.WdConstants.wdUndefined; level.Font.Superscript = (int)_Word.WdConstants.wdUndefined; level.Font.Shadow = (int)_Word.WdConstants.wdUndefined; level.Font.Outline = (int)_Word.WdConstants.wdUndefined; level.Font.Emboss = (int)_Word.WdConstants.wdUndefined; level.Font.Engrave = (int)_Word.WdConstants.wdUndefined; level.Font.AllCaps = (int)_Word.WdConstants.wdUndefined; level.Font.Hidden = (int)_Word.WdConstants.wdUndefined; level.Font.Underline = _Word.WdUnderline.wdUnderlineNone; level.Font.Color = _Word.WdColor.wdColorAutomatic; level.Font.Size = (int)_Word.WdConstants.wdUndefined; level.Font.Animation = _Word.WdAnimation.wdAnimationNone; level.Font.DoubleStrikeThrough = (int)_Word.WdConstants.wdUndefined; level.LinkedStyle = ""; //3-й уровень level = template.ListLevels[3]; level.NumberFormat = "%1.%2.%3."; level.TrailingCharacter = _Word.WdTrailingCharacter.wdTrailingTab; level.NumberStyle = _Word.WdListNumberStyle.wdListNumberStyleArabic; level.NumberPosition = WordApp.CentimetersToPoints(1.27f); level.Alignment = _Word.WdListLevelAlignment.wdListLevelAlignLeft; level.TextPosition = WordApp.CentimetersToPoints(2.16f); level.TabPosition = (float)_Word.WdConstants.wdUndefined; level.ResetOnHigher = 2; level.StartAt = 1; level.Font.Bold = 0; level.Font.Italic = (int)_Word.WdConstants.wdUndefined; level.Font.StrikeThrough = (int)_Word.WdConstants.wdUndefined; level.Font.Subscript = (int)_Word.WdConstants.wdUndefined; level.Font.Superscript = (int)_Word.WdConstants.wdUndefined; level.Font.Shadow = (int)_Word.WdConstants.wdUndefined; level.Font.Outline = (int)_Word.WdConstants.wdUndefined; level.Font.Emboss = (int)_Word.WdConstants.wdUndefined; level.Font.Engrave = (int)_Word.WdConstants.wdUndefined; level.Font.AllCaps = (int)_Word.WdConstants.wdUndefined; level.Font.Hidden = (int)_Word.WdConstants.wdUndefined; level.Font.Underline = _Word.WdUnderline.wdUnderlineNone; level.Font.Color = _Word.WdColor.wdColorAutomatic; level.Font.Size = (int)_Word.WdConstants.wdUndefined; level.Font.Animation = _Word.WdAnimation.wdAnimationNone; level.Font.DoubleStrikeThrough = (int)_Word.WdConstants.wdUndefined; level.LinkedStyle = ""; //4-й уровень level = template.ListLevels[4]; level.NumberFormat = "%1.%2.%3.%4."; level.TrailingCharacter = _Word.WdTrailingCharacter.wdTrailingTab; level.NumberStyle = _Word.WdListNumberStyle.wdListNumberStyleArabic; level.NumberPosition = WordApp.CentimetersToPoints(1.9f); level.Alignment = _Word.WdListLevelAlignment.wdListLevelAlignLeft; level.TextPosition = WordApp.CentimetersToPoints(3.05f); level.TabPosition = (float)_Word.WdConstants.wdUndefined; level.ResetOnHigher = 3; level.StartAt = 1; level.Font.Bold = 0; level.Font.Italic = (int)_Word.WdConstants.wdUndefined; level.Font.StrikeThrough = (int)_Word.WdConstants.wdUndefined; level.Font.Subscript = (int)_Word.WdConstants.wdUndefined; level.Font.Superscript = (int)_Word.WdConstants.wdUndefined; level.Font.Shadow = (int)_Word.WdConstants.wdUndefined; level.Font.Outline = (int)_Word.WdConstants.wdUndefined; level.Font.Emboss = (int)_Word.WdConstants.wdUndefined; level.Font.Engrave = (int)_Word.WdConstants.wdUndefined; level.Font.AllCaps = (int)_Word.WdConstants.wdUndefined; level.Font.Hidden = (int)_Word.WdConstants.wdUndefined; level.Font.Underline = _Word.WdUnderline.wdUnderlineNone; level.Font.Color = _Word.WdColor.wdColorAutomatic; level.Font.Size = (int)_Word.WdConstants.wdUndefined; level.Font.Animation = _Word.WdAnimation.wdAnimationNone; level.Font.DoubleStrikeThrough = (int)_Word.WdConstants.wdUndefined; level.LinkedStyle = ""; //5-й уровень level = template.ListLevels[5]; level.NumberFormat = "%1.%2.%3.%4.%5."; level.TrailingCharacter = _Word.WdTrailingCharacter.wdTrailingTab; level.NumberStyle = _Word.WdListNumberStyle.wdListNumberStyleArabic; level.NumberPosition = WordApp.CentimetersToPoints(2.54f); level.Alignment = _Word.WdListLevelAlignment.wdListLevelAlignLeft; level.TextPosition = WordApp.CentimetersToPoints(3.94f); level.TabPosition = (float)_Word.WdConstants.wdUndefined; level.ResetOnHigher = 4; level.StartAt = 1; level.Font.Bold = 0; level.Font.Italic = (int)_Word.WdConstants.wdUndefined; level.Font.StrikeThrough = (int)_Word.WdConstants.wdUndefined; level.Font.Subscript = (int)_Word.WdConstants.wdUndefined; level.Font.Superscript = (int)_Word.WdConstants.wdUndefined; level.Font.Shadow = (int)_Word.WdConstants.wdUndefined; level.Font.Outline = (int)_Word.WdConstants.wdUndefined; level.Font.Emboss = (int)_Word.WdConstants.wdUndefined; level.Font.Engrave = (int)_Word.WdConstants.wdUndefined; level.Font.AllCaps = (int)_Word.WdConstants.wdUndefined; level.Font.Hidden = (int)_Word.WdConstants.wdUndefined; level.Font.Underline = _Word.WdUnderline.wdUnderlineNone; level.Font.Color = _Word.WdColor.wdColorAutomatic; level.Font.Size = (int)_Word.WdConstants.wdUndefined; level.Font.Animation = _Word.WdAnimation.wdAnimationNone; level.Font.DoubleStrikeThrough = (int)_Word.WdConstants.wdUndefined; level.LinkedStyle = ""; template.Name = ""; for (int i = 0; i < textData.Rows.Count; i++) { for (int j = 0; j < 10; j++) { switch (j) { case 0: if (area != textData.Rows[i][j].ToString()) { area = textData.Rows[i][j].ToString(); relax = ""; j++; _Word.Paragraph oPara4; oPara4 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara4.Range.Font.Bold = 0; oPara4.Range.Font.Underline = _Word.WdUnderline.wdUnderlineSingle; oPara4.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara4.Range.Font.Name = "Times New Roman"; oPara4.Range.Font.Size = 14; //Размер шрифта абзаца oPara4.Range.Text = $"{area} ({textData.Rows[i][j]}):"; oPara4.Range.ListFormat.ApplyListTemplateWithLevel(template, false, _Word.WdListApplyTo.wdListApplyToWholeList, _Word.WdDefaultListBehavior.wdWord10ListBehavior); oPara4.Range.SetListLevel(1); oPara4.Range.InsertParagraphAfter(); } break; case 2: if (relax != textData.Rows[i][j].ToString()) { relax = textData.Rows[i][j].ToString(); doo = ""; j++; _Word.Paragraph oPara4; oPara4 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara4.Range.Font.Bold = 0; oPara4.Range.Font.Underline = _Word.WdUnderline.wdUnderlineNone; oPara4.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara4.Range.Font.Name = "Times New Roman"; oPara4.Range.Font.Size = 14; //Размер шрифта абзаца oPara4.Range.Text = $"{relax} ({textData.Rows[i][j]}):"; oPara4.Range.ListFormat.ApplyListTemplateWithLevel(template, false, _Word.WdListApplyTo.wdListApplyToWholeList, _Word.WdDefaultListBehavior.wdWord10ListBehavior); oPara4.Range.SetListLevel(2); oPara4.Range.InsertParagraphAfter(); } break; case 4: if (doo != textData.Rows[i][j].ToString()) { doo = textData.Rows[i][j].ToString(); help = ""; j++; _Word.Paragraph oPara4; oPara4 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara4.Range.Font.Bold = 0; oPara4.Range.Font.Underline = _Word.WdUnderline.wdUnderlineNone; oPara4.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara4.Range.Font.Name = "Times New Roman"; oPara4.Range.Font.Size = 14; //Размер шрифта абзаца oPara4.Range.Text = $"{doo} ({textData.Rows[i][j]}):"; oPara4.Range.ListFormat.ApplyListTemplateWithLevel(template, false, _Word.WdListApplyTo.wdListApplyToWholeList, _Word.WdDefaultListBehavior.wdWord10ListBehavior); oPara4.Range.SetListLevel(3); oPara4.Range.InsertParagraphAfter(); } break; case 6: if (help != textData.Rows[i][j].ToString()) { help = textData.Rows[i][j].ToString(); diag = ""; j++; _Word.Paragraph oPara4; oPara4 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara4.Range.Font.Bold = 0; oPara4.Range.Font.Underline = _Word.WdUnderline.wdUnderlineNone; oPara4.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara4.Range.Font.Name = "Times New Roman"; oPara4.Range.Font.Size = 14; //Размер шрифта абзаца oPara4.Range.Text = $"{help} ({textData.Rows[i][j]}):"; oPara4.Range.ListFormat.ApplyListTemplateWithLevel(template, false, _Word.WdListApplyTo.wdListApplyToWholeList, _Word.WdDefaultListBehavior.wdWord10ListBehavior); oPara4.Range.SetListLevel(4); oPara4.Range.InsertParagraphAfter(); } break; case 8: if (diag != textData.Rows[i][j].ToString()) { diag = textData.Rows[i][j].ToString(); j++; _Word.Paragraph oPara4; oPara4 = WordDoc.Content.Paragraphs.Add(); oPara4.Range.Font.Bold = 0; oPara4.Range.Font.Underline = _Word.WdUnderline.wdUnderlineNone; oPara4.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara4.Range.Font.Name = "Times New Roman"; oPara4.Range.Font.Size = 14; //Размер шрифта абзаца oPara4.Range.Text = $"{diag} - {textData.Rows[i][j]}"; oPara4.Range.ListFormat.ApplyListTemplateWithLevel(template, false, _Word.WdListApplyTo.wdListApplyToWholeList, _Word.WdDefaultListBehavior.wdWord10ListBehavior); oPara4.Range.SetListLevel(5); oPara4.Range.InsertParagraphAfter(); } break; } } } //WordDoc.Paragraphs[WordDoc.Paragraphs.Count].Range.Delete(); //Удаление последнего пустого абзаца WordDoc.Paragraphs[WordDoc.Paragraphs.Count].Format.Reset(); _Word.Paragraph oPara5 = WordDoc.Content.Paragraphs.Add(); /*_Word.Range wrdRng_1 = oPara5.Range; * _Word.Table oTable_1 = WordDoc.Tables.Add(wrdRng_1, 2, 2, ref oMissing, ref oMissing); * * var table = WordDoc.Tables[WordDoc.Tables.Count]; * table.set_Style("Сетка таблицы"); * table.ApplyStyleHeadingRows = true; * table.ApplyStyleLastRow = false; * table.ApplyStyleFirstColumn = true; * table.ApplyStyleLastColumn = false; * table.ApplyStyleRowBands = true; * table.ApplyStyleColumnBands = false;*/ _Word.Table oTable_1; _Word.Range wrdRng_1 = WordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable_1 = WordDoc.Tables.Add(wrdRng_1, 2 + classTable.Rows.Count, 14, ref oMissing, ref oMissing); // Размерность таблицы Nх10 (N - кол-во строк зависит от кол-ва строк в принимаемом аргументе, 10 столбцов) oTable_1.AutoFitBehavior(_Word.WdAutoFitBehavior.wdAutoFitFixed); // wdAutoFitFixed - фиксированный размер столбцов oTable_1.Rows.SetLeftIndent(-55, _Word.WdRulerStyle.wdAdjustNone); //Смещение таблицы влево на 75 единиц oTable_1.Range.ParagraphFormat.SpaceBefore = 6; oTable_1.Range.Bold = 0; //Выделение шрифта жирным oTable_1.Range.Font.Size = 10; //Размер шрифта в таблице oTable_1.Range.ParagraphFormat.SpaceAfter = 14; oTable_1.Range.ParagraphFormat.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphCenter; //Горизонтальное выравнивание текста по центру ячейки oTable_1.Range.Cells.VerticalAlignment = _Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //Вертикальное выравнивание текста в ячейке oTable_1.Borders.InsideLineStyle = _Word.WdLineStyle.wdLineStyleSingle; //Отрисовка сплошных линий внутри таблицы oTable_1.Borders.OutsideLineStyle = _Word.WdLineStyle.wdLineStyleSingle; //Отрисовка сплошных линий снаружи таблицы //Размеры столбцов в единицах oTable_1.Columns[1].Width = 90; //102 oTable_1.Columns[2].Width = 35; oTable_1.Columns[3].Width = 35; oTable_1.Columns[4].Width = 35; oTable_1.Columns[5].Width = 35; oTable_1.Columns[6].Width = 35; oTable_1.Columns[7].Width = 35; oTable_1.Columns[8].Width = 35; oTable_1.Columns[9].Width = 35; oTable_1.Columns[10].Width = 35; oTable_1.Columns[11].Width = 35; oTable_1.Columns[12].Width = 35; oTable_1.Columns[13].Width = 35; oTable_1.Columns[14].Width = 35; oTable_1.Rows[1].Height = 95; //Высота 1 строки в таблице oTable_1.Rows[1].Cells[1].Range.Text = "Территория"; oTable_1.Rows[1].Cells[2].Range.Text = "Травмы"; oTable_1.Rows[1].Cells[3].Range.Text = "Утопления"; oTable_1.Rows[1].Cells[4].Range.Text = "Инфекционные"; oTable_1.Rows[1].Cells[5].Range.Text = "Хирургические"; oTable_1.Rows[1].Cells[6].Range.Text = "Соматические"; oTable_1.Rows[1].Cells[7].Range.Text = "Нейрохирургические"; oTable_1.Rows[1].Cells[8].Range.Text = "Неврологические"; oTable_1.Rows[1].Cells[9].Range.Text = "ЛОР"; oTable_1.Rows[1].Cells[10].Range.Text = "Отравления"; oTable_1.Rows[1].Cells[11].Range.Text = "Алкогольные отравления"; oTable_1.Rows[1].Cells[12].Range.Text = "Наркотические отравления"; oTable_1.Rows[1].Cells[13].Range.Text = "Прочие"; oTable_1.Rows[1].Cells[14].Range.Bold = 1; oTable_1.Rows[1].Cells[14].Range.Text = "Всего"; /*oTable_1.Cell(1, 1).Merge(oTable.Cell(2, 1)); //Объединение 1 ячейки 1 строки с 1 ячейкой 2 строки * oTable_1.Cell(1, 2).Merge(oTable.Cell(2, 2)); //Объединение 2 ячейки 1 строки со 2 ячейкой 2 строки * oTable_1.Cell(1, 3).Merge(oTable.Cell(1, 4)); //Объединение 3 ячейки 1 строки с 4 ячейкой 1 строки * oTable_1.Cell(1, 4).Merge(oTable.Cell(1, 5)); //Объединение 4 ячейки 1 строки с 5 ячейкой 1 строки * oTable_1.Cell(1, 5).Merge(oTable.Cell(2, 7)); //Объединение 5 ячейки 1 строки с 7 ячейкой 2 строки * oTable_1.Cell(1, 6).Merge(oTable.Cell(2, 8)); //Объединение 6 ячейки 1 строки с 8 ячейкой 2 строки * oTable_1.Cell(1, 7).Merge(oTable.Cell(2, 9)); //Объединение 7 ячейки 1 строки с 9 ячейкой 2 строки * oTable_1.Cell(1, 8).Merge(oTable.Cell(2, 10)); //Объединение 8 ячейки 1 строки с 10 ячейкой 2 строки*/ for (int i = 2; i <= 14; i++) { oTable_1.Cell(1, i).Range.Orientation = _Word.WdTextOrientation.wdTextOrientationUpward; //Направление текста вверх на 90 градусов } //oTable_1.Cell(1, 3).Range.Orientation = _Word.WdTextOrientation.wdTextOrientationUpward; //Направление текста вверх на 90 градусов //oTable_1.Cell(2, 5).Range.Orientation = _Word.WdTextOrientation.wdTextOrientationUpward; //Направление текста вверх на 90 градусов //oTable_1.Cell(2, 6).Range.Orientation = _Word.WdTextOrientation.wdTextOrientationUpward; //Направление текста вверх на 90 градусов for (int i = 0; i < classTable.Rows.Count; i++) { for (int j = 0; j <= 12; j++) { oTable_1.Cell(i + 2, j + 1).Range.Text = classTable.Rows[i][j].ToString(); } } for (int i = 2; i < oTable_1.Rows.Count; i++) { int sumColumn = 0; for (int j = 2; j <= 13; j++) { string _char = oTable_1.Cell(i, j).Range.Text.ToString(); _char = _char.Remove(_char.Length - 2, 2); sumColumn += int.Parse(_char); } oTable_1.Cell(i, 14).Range.Bold = 1; oTable_1.Cell(i, 14).Range.Text = sumColumn.ToString(); } oTable_1.Cell(2 + classTable.Rows.Count, 1).Range.Bold = 1; oTable_1.Cell(2 + classTable.Rows.Count, 1).Range.Text = "Итого"; for (int j = 2; j <= 14; j++) { int sumColumn = 0; for (int i = 2; i < oTable_1.Rows.Count; i++) { string _char = oTable_1.Cell(i, j).Range.Text.ToString(); _char = _char.Remove(_char.Length - 2, 2); sumColumn += int.Parse(_char); } oTable_1.Cell(2 + wordData.Rows.Count, j).Range.Bold = 1; oTable_1.Cell(2 + wordData.Rows.Count, j).Range.Text = sumColumn.ToString(); } _Word.Paragraph oPara6; oPara6 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara6.Range.Font.Bold = 0; oPara6.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara6.Range.Font.Name = "Times New Roman"; oPara6.Range.Font.Size = 14; //Размер шрифта абзаца oPara6.Format.SpaceAfter = 14; string itog_1 = oTable_1.Cell(oTable_1.Rows.Count, 14).Range.Text.ToString(); itog_1 = itog_1.Remove(itog_1.Length - 2, 2); string itog_list = ""; for (int i = 2; i <= 13; i++) { string sum = oTable_1.Cell(oTable_1.Rows.Count, i).Range.Text; sum = sum.Remove(sum.Length - 2, 2); string chld = ""; if (int.Parse(sum) > 0) { switch (int.Parse(sum.Substring(sum.Length - 1))) { case 1: chld = "ребенок"; break; case 2: case 3: case 4: chld = "ребенка"; break; default: chld = "детей"; break; } } if (i == 2) { if (int.Parse(sum) > 0) { itog_list = $"- {oTable_1.Cell(1, i).Range.Text.Remove(oTable_1.Cell(1, i).Range.Text.Length - 2, 2)} - {sum} {chld} ({Math.Round((double.Parse(sum) * 100) / double.Parse(itog_1),1)}%); \r\n"; } } else { if (int.Parse(sum) > 0) { itog_list += $"- {oTable_1.Cell(1, i).Range.Text.Remove(oTable_1.Cell(1, i).Range.Text.Length - 2, 2)} - {sum} {chld} ({Math.Round((double.Parse(sum) * 100) / double.Parse(itog_1), 1)}%); \r\n"; } } } string all_chld = ""; if (int.Parse(itog_1) > 0) { switch (int.Parse(itog_1.Substring(itog_1.Length - 1))) { case 1: all_chld = "ребенок"; break; case 2: case 3: case 4: all_chld = "ребенка"; break; default: all_chld = "детей"; break; } } if (PeriodDateFrom.ToString("MMMMyyyy") == PeriodDateTo.ToString("MMMMyyyy")) { oPara6.Range.Text = $"За {PeriodDateTo:MMMM yyyy} года включительно из детских оздоровительных организаций всех форм собственности в медицинские организации края обратилось(ись) {itog_1} {all_chld}, в том числе:\r\n{itog_list}"; } else if (PeriodDateFrom.ToString("yyyy") == PeriodDateTo.ToString("yyyy")) { oPara6.Range.Text = $"За {PeriodDateFrom:MMMM}-{PeriodDateTo:MMMM yyyy} года включительно из детских оздоровительных организаций всех форм собственности в медицинские организации края обратилось(ись) {itog_1} {all_chld}, в том числе:\r\n{itog_list}"; } else { oPara6.Range.Text = $"За {PeriodDateFrom:MMMM yyyy}-{PeriodDateTo:MMMM yyyy} года включительно из детских оздоровительных организаций всех форм собственности в медицинские организации края обратилось(ись) {itog_1} {all_chld}, в том числе:\r\n{itog_list}"; } oPara6.Range.InsertParagraphAfter(); string report_chld_org = ""; string report_chld_nonorg = ""; for (int i = 0; i < CHLDReport.Rows.Count; i++) { string str = CHLDReport.Rows[i][1].ToString(); switch (CHLDReport.Rows[i][0].ToString()) { case "Организованный отдых": switch (int.Parse(str.Substring(str.Length - 1))) { case 1: report_chld_org = "ребенку"; break; default: report_chld_org = "детям"; break; } break; case "Неорганизованный отдых": switch (int.Parse(str.Substring(str.Length - 1))) { case 1: report_chld_nonorg = "ребенку"; break; default: report_chld_nonorg = "детям"; break; } break; } } if (CHLDReport.Rows.Count > 1) { _Word.Paragraph oPara7; oPara7 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara7.Range.Font.Bold = 0; oPara7.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara7.Range.Font.Name = "Times New Roman"; oPara7.Range.Font.Size = 14; //Размер шрифта абзаца oPara7.Format.SpaceAfter = 14; oPara7.Range.Text = $"{CHLDReport.Rows[0][0]} - специализированная медицинская помощь оказана {CHLDReport.Rows[0][1]} {report_chld_org}."; oPara7.Range.InsertParagraphAfter(); _Word.Paragraph oPara8; oPara8 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara8.Range.Font.Bold = 0; oPara8.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara8.Range.Font.Name = "Times New Roman"; oPara8.Range.Font.Size = 14; //Размер шрифта абзаца oPara8.Format.SpaceAfter = 14; oPara8.Range.Text = $"{CHLDReport.Rows[1][0]} - специализированная медицинская помощь оказана {CHLDReport.Rows[1][1]} {report_chld_nonorg}."; oPara8.Range.InsertParagraphAfter(); } else if (CHLDReport.Rows.Count == 1) { _Word.Paragraph oPara7; oPara7 = WordDoc.Content.Paragraphs.Add(ref oMissing); oPara7.Range.Font.Bold = 0; oPara7.Range.Paragraphs.Alignment = _Word.WdParagraphAlignment.wdAlignParagraphJustify; oPara7.Range.Font.Name = "Times New Roman"; oPara7.Range.Font.Size = 14; //Размер шрифта абзаца oPara7.Format.SpaceAfter = 14; oPara7.Range.Text = $"{CHLDReport.Rows[0][0]} - специализированная медицинская помощь оказана {CHLDReport.Rows[0][1]} {report_chld_org}."; oPara7.Range.InsertParagraphAfter(); } // WordDoc.Paragraphs[WordDoc.Paragraphs.Count].Range.Delete(); //Удаление последнего пустого абзаца WordApp.Visible = true; } catch (Exception ex) { logger.Error(ex, $"\r\n#---------#\r\n{ex.StackTrace}\r\n##---------##\r\n{ex.Message}\r\n###---------###\r\n{ex.Source}"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public WordSpecExport(CopyToClipboard cpc, BackgroundWorker ExportWorker, string filename) { Microsoft.Office.Interop.Word.Application oWord = null; Microsoft.Office.Interop.Excel.Application oExcel = null; try { List <SveraClass.FromDataBaseWide> rowgrid = SveraCl.PereformSpec(cpc, TypeOfExport.WordSpec); // return; int maxofprog = rowgrid.Count + 2 * 8; maxofprog += rowgrid.Count; int counter = 0; ExportWorker.ReportProgress(maxofprog, Operation.init); string exportPath = FunctionUse.GetExportPath(filename); try { exportPath += "\\"; exportPath += (filename != null && filename != "") ? Path.GetFileNameWithoutExtension(filename) : "specification"; exportPath += ".docx"; if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.standart) { File.WriteAllBytes(exportPath, SveraExport.Properties.Resources.Specification); } else if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.rev) { File.WriteAllBytes(exportPath, SveraExport.Properties.Resources.specification_del); } } catch (Exception ex) { MessageBox.Show("Файл открыт и используется. Закройте файл и повторите попытку", "Svera Export Word", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Microsoft.Office.Interop.Word.Document oDoc; Microsoft.Office.Interop.Excel.Workbook oBook; Microsoft.Office.Interop.Excel.Worksheet oSheet; //Microsoft.Office.Interop.Word.Table oTable; //Microsoft.Office.Interop.Word.Paragraph oPara1; counter += 2; ExportWorker.ReportProgress(counter, Operation.change); if (ExportWorker.CancellationPending) { ExitWord(oWord, oExcel, true); return; } try { oWord = new Microsoft.Office.Interop.Word.Application(); oDoc = oWord.Documents.Open(exportPath); oExcel = new Microsoft.Office.Interop.Excel.Application(); oBook = oExcel.Workbooks.Add(); oSheet = oExcel.Worksheets[1]; podgotovWord(oWord, oExcel, false, false); oDoc.SaveAs(exportPath); oBook.SaveAs(Path.GetDirectoryName(exportPath) + "\\" + Path.GetFileNameWithoutExtension(exportPath) + ".xlsx"); } catch (Exception ex) { MessageBox.Show("Файл " + Path.GetDirectoryName(exportPath) + "\\" + Path.GetFileNameWithoutExtension(exportPath) + " уже открыт. Закройте файл. Повторите попытку", "Svera Export Word", MessageBoxButtons.OK, MessageBoxIcon.Information); ExitWord(oWord, oExcel, true); return; } counter += 2; ExportWorker.ReportProgress(counter, Operation.change); if (ExportWorker.CancellationPending) { ExitWord(oWord, oExcel, true); return; } oSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape; oDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape; oDoc.AutoHyphenation = true; oDoc.Content.Font.Name = "Times New Roman"; oDoc.Content.Font.Size = 10; int numberCOl = 9; if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.standart) { numberCOl = 9; } else if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.rev) { numberCOl = 11; } string[,] OtableStr = new string[rowgrid.Count, numberCOl]; if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.standart) { oSheet.Columns[1].ColumnWidth = 5; oSheet.Columns[2].ColumnWidth = 30; oSheet.Columns[3].ColumnWidth = 20; oSheet.Columns[4].ColumnWidth = 12; oSheet.Columns[5].ColumnWidth = 15; oSheet.Columns[6].ColumnWidth = 5; oSheet.Columns[7].ColumnWidth = 7; oSheet.Columns[8].ColumnWidth = 8; oSheet.Columns[9].ColumnWidth = 15; } else if (cpc.ExportP.TipSpec == SveraExportParam.RowsDatagridExportNames.TipSpecAndVed.rev) { oSheet.Columns[1].ColumnWidth = 5; oSheet.Columns[2].ColumnWidth = 30; oSheet.Columns[3].ColumnWidth = 20; oSheet.Columns[4].ColumnWidth = 8; oSheet.Columns[5].ColumnWidth = 8; oSheet.Columns[6].ColumnWidth = 10; oSheet.Columns[7].ColumnWidth = 8; oSheet.Columns[8].ColumnWidth = 8; oSheet.Columns[9].ColumnWidth = 8; oSheet.Columns[10].ColumnWidth = 8; oSheet.Columns[11].ColumnWidth = 12; } counter += 2; ExportWorker.ReportProgress(counter, Operation.change); if (ExportWorker.CancellationPending) { ExitWord(oWord, oExcel, true); return; } int numberRow = 0; for (int i = 0; i <= rowgrid.Count - 1; i++) { addrowInSpec(cpc, rowgrid[i], OtableStr, oSheet, ref numberRow); } counter += 2; ExportWorker.ReportProgress(counter, Operation.change); if (ExportWorker.CancellationPending) { ExitWord(oWord, oExcel, true); return; } if (rowgrid.Count > 0) { Microsoft.Office.Interop.Excel.Range rangeEx = oSheet.Range[oSheet.Cells[1, 1], oSheet.Cells[OtableStr.GetUpperBound(0) + 1, OtableStr.GetUpperBound(1) + 1]]; rangeEx.Value = OtableStr; rangeEx.Font.Name = "Times New Roman"; rangeEx.Font.Size = 10; rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; rangeEx.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; rangeEx.WrapText = true; } counter += 2; ExportWorker.ReportProgress(counter, Operation.change); if (ExportWorker.CancellationPending) { ExitWord(oWord, oExcel, true); return; } if (rowgrid.Count > 0) { for (int i = 1; i <= OtableStr.GetUpperBound(1) + 1; i++) { if (i != 2 && i != 3) { oSheet.Columns[i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; oSheet.Columns[i].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; } else { oSheet.Columns[i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; oSheet.Columns[i].VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; } } counter += 2; ExportWorker.ReportProgress(counter, Operation.change); if (ExportWorker.CancellationPending) { ExitWord(oWord, oExcel, true); return; } } for (int i = 0; i <= rowgrid.Count - 1; i++) { if (rowgrid[i].RowTypes == RowsType.TipOborud) { oSheet.Cells[i + 1, 2].Font.Bold = true; oSheet.Cells[i + 1, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; } else if (rowgrid[i].RowTypes == RowsType.TipPostav) { oSheet.Cells[i + 1, 2].Font.Bold = true; oSheet.Cells[i + 1, 2].Font.Underline = Microsoft.Office.Interop.Excel.XlUnderlineStyle.xlUnderlineStyleSingle; oSheet.Cells[i + 1, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; } else if (rowgrid[i].RowTypes == RowsType.Etap) { oSheet.Cells[i + 1, 2].Font.Bold = true; oSheet.Cells[i + 1, 2].Font.Underline = Microsoft.Office.Interop.Excel.XlUnderlineStyle.xlUnderlineStyleSingle; oSheet.Cells[i + 1, 2].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; } } counter += 2; ExportWorker.ReportProgress(counter, Operation.change); if (ExportWorker.CancellationPending) { ExitWord(oWord, oExcel, true); return; } oSheet.Rows.AutoFit(); oExcel.ActiveWindow.SplitColumn = 0; oExcel.ActiveWindow.SplitRow = 2; oExcel.ActiveWindow.FreezePanes = true; oExcel.ActiveWindow.Zoom = 82; Microsoft.Office.Interop.Word.Style Stylus = oWord.Selection.get_Style(); Stylus.Font.Name = "Times New Roman"; Stylus.Font.Size = 10; Stylus.ParagraphFormat.SpaceBefore = 0; Stylus.ParagraphFormat.SpaceAfter = 0; if (rowgrid.Count > 0) { oSheet.Range[oSheet.Cells[1, 1], oSheet.Cells[OtableStr.GetUpperBound(0) + 1, OtableStr.GetUpperBound(1) + 1]].Copy(); } oWord.Selection.Paste(); oExcel.CutCopyMode = XlCutCopyMode.xlCopy; if (oDoc.Tables.Count > 1) { oDoc.Tables[1].Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast; oDoc.Tables[1].Rows.Height = oWord.CentimetersToPoints(0.58F); oDoc.Tables[1].AllowAutoFit = false; oDoc.Tables[1].LeftPadding = oDoc.Tables[2].LeftPadding; oDoc.Tables[1].RightPadding = oDoc.Tables[2].RightPadding; if (oDoc.Tables[2].Columns.Count >= numberCOl && oDoc.Tables[1].Columns.Count >= numberCOl) { for (int i = 1; i <= numberCOl; i++) { oDoc.Tables[1].Columns[i].Width = oDoc.Tables[2].Columns[i].Width; } } oDoc.Tables[2].Delete(); oDoc.Tables[1].Rows.SetLeftIndent(oWord.CentimetersToPoints(0.03F), Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustNone); } counter += 2; ExportWorker.ReportProgress(counter, Operation.change); if (ExportWorker.CancellationPending) { ExitWord(oWord, oExcel, true); return; } oDoc.Save(); oBook.Save(); ExitWord(oWord, oExcel, false); oWord = null; oExcel = null; } catch (Exception ex) { ExitWord(oWord, oExcel, false); throw new Exception("WordExport", ex); } }
/// <summary> /// 修改表格样式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TableFormat_Click(object sender, RibbonControlEventArgs e) { //弹出窗体提示 DialogResult IsWait = MessageBox.Show("如果表格较多运行较为缓慢,进度可在Word左下角查看" + Environment.NewLine + "是否继续?", "请选择", MessageBoxButtons.YesNo); if (IsWait != DialogResult.Yes) { return; } WordApp = Globals.ThisAddIn.Application; WordDoc = WordApp.ActiveDocument; WordApp.ScreenUpdating = false; //关闭屏幕刷新 #region //读取配置文件 //读取配置文件 ClsThisAddinConfig clsConfig = new ClsThisAddinConfig(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)); //表格间距 bool SpaceGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "SpaceGroupCheck", true); //首行缩进 bool TableIndentCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableIndentCheck", true); //段前 decimal TableBeforeMainBody = clsConfig.ReadConfig <decimal>("SettingFormatForm", "TableBeforeMainBody", 0m); //段后 decimal TableAfterMainBody = clsConfig.ReadConfig <decimal>("SettingFormatForm", "TableAfterMainBody", 0m); //行间距 decimal TableRowSpace = FormatFunC.RowSpace(clsConfig.ReadConfig <string>("SettingFormatForm", "TableRowSpace", "单倍行距")); //表格边框 bool BorderGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "BorderGroupCheck", true); //上下边框宽度1磅 bool TableTBBorderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableTBBorderCheck", true); //左右无边框 bool TableLRBorderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableLRBorderCheck", true); //表格其他选项 bool OtherGroupCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "OtherGroupCheck", true); //垂直居中 bool TableVerticalCenterCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableVerticalCenterCheck", true); //标题及合计行加粗 bool TableTitleWiderCheck = clsConfig.ReadConfig <bool>("SettingFormatForm", "TableTitleWiderCheck", true); //表格字号 decimal TableFontSize = FormatFunC.FontSize(clsConfig.ReadConfig <string>("SettingFormatForm", "TableFontSize", "小四")); #endregion if (SpaceGroupCheck || BorderGroupCheck || OtherGroupCheck) { //在状态栏显示进度 WordApp.StatusBar = "当前进度:0%"; int i3 = WordDoc.Tables.Count; int i4 = 1; foreach (Word.Table Tb in WordDoc.Tables) { Tb.Select(); //间距 if (SpaceGroupCheck) { if (TableIndentCheck) { WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = 0; WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = 0; WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 0; WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints(0); } WordApp.Selection.ParagraphFormat.SpaceBefore = 0; WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse(TableBeforeMainBody.ToString()); WordApp.Selection.ParagraphFormat.SpaceAfter = 0; WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse(TableAfterMainBody.ToString()); WordApp.Selection.ParagraphFormat.LineSpacing = WordApp.LinesToPoints(float.Parse(TableRowSpace.ToString())); WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = -1; //行距设置中,不勾选“如果定义了文档网格,则于网格对齐” WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = -1; //行距设置中,不勾选“如果定义了文档网格,则自动调整右缩进” } //边框 if (BorderGroupCheck) { //上下边框1磅 if (TableTBBorderCheck) { Tb.Borders[Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleSingle; Tb.Borders[Word.WdBorderType.wdBorderTop].LineWidth = Word.WdLineWidth.wdLineWidth100pt; Tb.Borders[Word.WdBorderType.wdBorderTop].Color = Word.WdColor.wdColorAutomatic; Tb.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle; Tb.Borders[Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth100pt; Tb.Borders[Word.WdBorderType.wdBorderBottom].Color = Word.WdColor.wdColorAutomatic; } //左右无边框 if (TableLRBorderCheck) { Tb.Borders[Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleNone; Tb.Borders[Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleNone; } } //其他选项 if (OtherGroupCheck) { //垂直居中 if (TableVerticalCenterCheck) { WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; } // if (TableTitleWiderCheck) { } //表格字体 Tb.Range.Font.Size = float.Parse(TableFontSize.ToString()); } //显示进度 WordApp.StatusBar = "当前进度:" + Math.Round((i4 * 100d / i3), 2) + "%"; i4++; } } WordApp.ScreenUpdating = true;//关闭屏幕刷新 }
public CreateDocument(String [] Section_1, String[] Section_2, String[] Section_3, String[] Section_4, String[] SignaturAndDate) { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = false; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; //Section 0: Title Section Word.Paragraph Title_Section; Title_Section = oDoc.Content.Paragraphs.Add(ref oMissing); Title_Section.Range.Font.Size = 16; Title_Section.Range.Bold = 1; Title_Section.Range.Text = "e-Commerce/EDI SI5 Promotion Check List"; Title_Section.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; Title_Section.Range.InsertParagraphAfter(); //Section 1: User Partner Section--------------------------------------------------------------------------------------------------------- Word.Paragraph UserPartner_Section; UserPartner_Section = oDoc.Content.Paragraphs.Add(ref oMissing); UserPartner_Section.Range.Text = "User: "******"\t\t"); UserPartner_Section.Range.InsertAfter("Partner: " + Section_1[1]); UserPartner_Section.Range.InsertAfter("\t\t"); UserPartner_Section.Range.InsertAfter("Date: " + Section_1[2]); UserPartner_Section.Range.InsertAfter("\n"); UserPartner_Section.Range.InsertAfter("Title: " + Section_1[3]); UserPartner_Section.Range.InsertAfter("\t\t"); UserPartner_Section.Range.InsertAfter("Change Management Request Number: " + Section_1[4]); UserPartner_Section.Range.InsertParagraphAfter(); //Section 2: User Signoff Checklist Section------------------------------------------------------------------------------------------------------ Word.Table UserCheckList; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; UserCheckList = oDoc.Tables.Add(wrdRng, 10, 4, ref oMissing, ref oMissing); UserCheckList.Range.ParagraphFormat.SpaceAfter = 6; UserCheckList.AllowAutoFit = true; UserCheckList.Columns[1].SetWidth(oWord.CentimetersToPoints(6f), Word.WdRulerStyle.wdAdjustNone); UserCheckList.Range.Font.Size = 10; Word.Column first = UserCheckList.Columns[1]; int checklist = 0; for (int r = 1; r <= 10; r++) { for (int c = 1; c <= 4; c++) { UserCheckList.Cell(r, c).Range.Text = Section_2[checklist]; checklist++; } } //Section 3: User Signoff Checklist Section-------------------------------------------------------------------------------------------------------------- //Insert another paragraph. Word.Paragraph oPara3; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); oPara3.Range.Text = " ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"; oPara3.Range.Font.Bold = 0; oPara3.Range.Font.Size = 8; oPara3.Range.InsertParagraphAfter(); Word.Table Checklist; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3.Range.Paragraphs.LineSpacing = 10f; Checklist = oDoc.Tables.Add(wrdRng, 15, 4, ref oMissing, ref oMissing); Checklist.Range.ParagraphFormat.SpaceAfter = 6; Checklist.Columns[1].SetWidth(oWord.CentimetersToPoints(5f), Word.WdRulerStyle.wdAdjustNone); Checklist.AllowAutoFit = true; checklist = 0; for (int r = 1; r <= 15; r++) { for (int c = 1; c <= 4; c++) { Checklist.Cell(r, c).Range.Text = Section_3[checklist]; checklist++; } } //Section 4: Schedule //Insert another paragraph. Word.Paragraph oPara4; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara4 = oDoc.Content.Paragraphs.Add(ref oRng); oPara4.Range.Font.Size = 8; oPara4.Range.Text = "--------------------------------------------------------------------------------------------------------------------------------------------------------"; oPara4.Range.Font.Bold = 0; oPara4.Range.InsertParagraphAfter(); Word.Table FinalCheckList; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara4.Range.Paragraphs.LineSpacing = 10f; FinalCheckList = oDoc.Tables.Add(wrdRng, 3, 4, ref oMissing, ref oMissing); FinalCheckList.Range.ParagraphFormat.SpaceAfter = 6; FinalCheckList.Columns[1].SetWidth(oWord.CentimetersToPoints(5f), Word.WdRulerStyle.wdAdjustNone); FinalCheckList.AllowAutoFit = true; checklist = 0; for (int r = 1; r <= 3; r++) { for (int c = 1; c <= 4; c++) { FinalCheckList.Cell(r, c).Range.Text = Section_4[checklist]; checklist++; } } //Signature and Date Section //Insert another paragraph. Word.Paragraph SignatureAndDate_Section; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; SignatureAndDate_Section = oDoc.Content.Paragraphs.Add(ref oRng); SignatureAndDate_Section.Range.Font.Bold = 0; SignatureAndDate_Section.Range.InsertParagraphAfter(); SignatureAndDate_Section.Range.Text = "\n\t\t\t\t\t\t\tProject Manager: " + SignaturAndDate[0]; SignatureAndDate_Section.Range.InsertAfter("\n\n"); SignatureAndDate_Section.Range.InsertAfter("\t\t\t\t\t\t\tCompletion Date: " + SignaturAndDate[1]); String filename = @"C:\SharePoint Upload\Checklist_" + Section_2[37].Replace(" ", "") + "_" + DateTime.Now.ToString("yyyyMMdd") + ".docx"; oWord.ActiveDocument.SaveAs2(filename);//Grabs the Implementation from Post Implementation oWord.ActiveDocument.Close(); }
private void SaveAsWordDocument() { DateTime beginSessionDate, endSessionDate; DetectSessionDates(out beginSessionDate, out endSessionDate); object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. Word._Application oWord = new Word.Application(); oWord.Visible = true; Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); var faculties = _sRepo.GetAllFaculties(); for (int facCounter = 0; facCounter < Constants.Constants.facultyGroups.Keys.Count; facCounter++) { var groupIds = new List<int>(); foreach (var group in Constants.Constants.facultyGroups.ElementAt(facCounter).Value) { var groupId = _sRepo.FindStudentGroup(group); if (groupId != null) { groupIds.Add(groupId.StudentGroupId); } } var facultyExams = _repo.GetFacultyExams(_sRepo, groupIds); facultyExams = facultyExams.OrderBy(fe => fe.Key).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value); Word.Paragraph oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Font.Size = 24; oPara1.Format.LineSpacing = oWord.LinesToPoints(1); oPara1.Range.Text = "Расписание"; oPara1.Format.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Font.Size = 14; oPara1.Format.SpaceAfter = 0; if (beginSessionDate.Month < 3) { var startYear = beginSessionDate.Year - 1; oPara1.Range.Text = "зимней сессии " + startYear + "-" + (startYear + 1) + " учебного года" + Environment.NewLine + Constants.Constants.facultyTitles[facCounter]; } else { var startYear = beginSessionDate.Year - 1; oPara1.Range.Text = "летней сессии " + startYear + "-" + (startYear + 1) + " учебного года" + Environment.NewLine + Constants.Constants.facultyTitles[facCounter]; } oPara1.Range.InsertParagraphAfter(); Word.Shape signBox = oDoc.Shapes .AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350, 15, 200, 75, oPara1.Range); signBox.Line.Visible = MsoTriState.msoFalse; signBox.TextFrame.ContainingRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; signBox.TextFrame.ContainingRange.InsertAfter("«УТВЕРЖДАЮ»"); signBox.TextFrame.ContainingRange.InsertParagraphAfter(); signBox.TextFrame.ContainingRange.InsertAfter("Проректор по учебной работе"); signBox.TextFrame.ContainingRange.InsertParagraphAfter(); signBox.TextFrame.ContainingRange.InsertAfter("____________ А.В. Синицкий"); var groups = Constants.Constants.facultyGroups.ElementAt(facCounter).Value; Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 1 + facultyExams.Keys.Count, 1 + groups.Count); //oTable.Rows(1).HeadingFormat = True; //oTable.ApplyStyleHeadingRows = True; oTable.Rows[1].HeadingFormat = -1; oTable.ApplyStyleHeadingRows = true; oTable.Borders.Enable = 1; for (int i = 1; i <= oTable.Rows.Count; i++) { oTable.Rows[i].AllowBreakAcrossPages = (int)Microsoft.Office.Core.MsoTriState.msoFalse; } oTable.Cell(1, 1).Range.Text = "Дата"; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; for (var column = 1; column <= groups.Count; column++) { oTable.Cell(1, column + 1).Range.Text = groups[column - 1]; oTable.Cell(1, column + 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++) { oTable.Cell(row, 1).Range.Text = facultyExams.Keys.ElementAt(row - 2).ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU")); oTable.Cell(row, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(row, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } DateTime currentDate; for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++) { currentDate = facultyExams.Keys.ElementAt(row - 2); for (var column = 1; column <= groups.Count; column++) { if (facultyExams.ContainsKey(currentDate)) { if (facultyExams[currentDate].ContainsKey(groupIds[column - 1])) { var eventCount = facultyExams[currentDate][groupIds[column - 1]].Count; oTable.Cell(row, column + 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; var timeTable = oDoc.Tables.Add(oTable.Cell(row, column + 1).Range, 1, 1); timeTable.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow); if (eventCount > 1) { for (int i = 1; i < eventCount; i++) { timeTable.Rows.Add(); } } for (int i = 0; i < eventCount; i++) { string cellText = ""; var evt = facultyExams[currentDate][groupIds[column - 1]][i]; // Консультация || Экзамен if (evt.IsExam) { cellText += "Экзамен"; } else { cellText += "Консультация"; } cellText += Environment.NewLine; cellText += evt.DisciplineName + Environment.NewLine; cellText += evt.TeacherFIO + Environment.NewLine; cellText += evt.Time.ToString("H:mm") + Environment.NewLine; cellText += evt.Auditorium; oPara1 = oDoc.Content.Paragraphs.Add(timeTable.Cell(i + 1, 1).Range); oPara1.Range.Font.Size = 10; oPara1.Format.SpaceAfter = 0; oPara1.Range.Text = cellText; if (i != eventCount - 1) { timeTable.Cell(i + 1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = true; } } } } } } oTable.Columns[1].Width = oWord.CentimetersToPoints(3); for (int i = 0; i < groups.Count; i++) { oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(16 / groups.Count); } oTable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter; Word.Paragraph oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = ""; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = "Начальник учебного отдела\t\t" + "_________________ " + Constants.Constants.UchOtdHead; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2.Range.InsertParagraphAfter(); oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = "Декан " + Constants.Constants.facultyTitles[facCounter] + "\t\t_________________ " + Constants.Constants.HeadsOfFaculties.ElementAt(facCounter).Value; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2.Range.InsertParagraphAfter(); if (facCounter != Constants.Constants.facultyGroups.Keys.Count - 1) { oDoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak); } Application.DoEvents(); } object fileName = Application.StartupPath + @"\Export2.docx"; //oDoc.SaveAs(ref fileName); //oWord.Quit(); }
/// <summary> /// Метод создания и сохранения документов /// в форматах Microsoft Word (doc, PDF), /// Excel (exls) /// </summary> /// <param name="type">Тип создаваемого документа /// отчёт или статистика</param> /// <param name="format">Формат сохранения /// документ или таблица</param> /// <param name="name">Название документа</param> /// <param name="table">Входная таблица с данными</param> public void Document_Create(Document_Type type, Document_Format format, string name, DataTable table) { //Получение данных о конфигурации документа Configuration_class configuration_Class = new Configuration_class(); configuration_Class.Document_Configuration_Get(); //Проверка на пустоту названия switch (name != "" || name != null) { case true: //Выбор формата либо Word либо Excel switch (format) { case Document_Format.Word: //Запуск процесса в дистпечере задач word.Application application = new word.Application(); //создание документа в процессе word.Document document //Присвоение документа процессу, Visible: true //возможность редактирования документа = application.Documents.Add(Visible: true); try { //Объявление дипапазона для формирования текста word.Range range = document.Range(0, 0); //89Настройка отступов в документе document.Sections.PageSetup.LeftMargin = application.CentimetersToPoints( (float)Configuration_class. doc_Left_Merge); document.Sections.PageSetup.TopMargin = application.CentimetersToPoints( (float)Configuration_class. doc_Top_Merge); document.Sections.PageSetup.RightMargin = application. CentimetersToPoints((float) Configuration_class.doc_Right_Merg); document.Sections.PageSetup.BottomMargin = application.CentimetersToPoints( (float)Configuration_class. doc_Bottom_Merge); //Присвоение текстового знеачения в дипазон range.Text = "Мвидео"; //Настройка выравнивания текста range.ParagraphFormat.Alignment = word.WdParagraphAlignment. wdAlignParagraphCenter; //Настройка интервала после абзаца range.ParagraphFormat.SpaceAfter = 1; //Настройка интервала перед абзаца range.ParagraphFormat.SpaceBefore = 1; //Настройка межстрочного интервала range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle; //Настройка названия шрифта range.Font.Name = "Times New Roman"; //Настройка размера шрифта range.Font.Size = 12; //Добавление параграфов document.Paragraphs.Add(); //В конце текста document.Paragraphs.Add(); //Свободный document.Paragraphs.Add(); //Для будущего текста //Параграф для названия документа word.Paragraph Document_Name = document.Paragraphs.Add(); //Настройка параграфа через свойство диапазона Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; Document_Name.Range.Font.Name = "Times New Roman"; Document_Name.Range.Font.Size = 16; //Проверка на тип документа, отчёт или статистика switch (type) { case Document_Type.Report: Document_Name.Range.Text = "ОТЧЁТ"; break; case Document_Type.Statistic: Document_Name.Range.Text = "СТАТИСТИЧЕСКИЙ ОТЧЁТ"; break; } document.Paragraphs.Add(); document.Paragraphs.Add(); document.Paragraphs.Add(); word.Paragraph statparg = document.Paragraphs.Add(); //Создание области таблицы в документе word.Table stat_table //Добавление таблицы в область документа //Указывается параграф в котором документ создан //Количество строк и столбцов = document.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count); //Настройка границ таблицы внутренние stat_table.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; //Настройка границ таблицы внешние stat_table.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; //Выравнивание текста внутри ячеек по ширине stat_table.Rows.Alignment = word.WdRowAlignment.wdAlignRowCenter; //Выравнивание текста внутри ячеек по высоте stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; stat_table.Range.Font.Size = 11; stat_table.Range.Font.Name = "Times New Roman"; //Индексация столбцов и строк в Word начинается с 1,1 for (int row = 1; row <= table.Rows.Count; row++) { for (int col = 1; col <= table.Columns.Count; col++) { stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString(); } } document.Paragraphs.Add(); document.Paragraphs.Add(); //Парадграф с фиксациейц даты создания документа word.Paragraph Footparg = document.Paragraphs.Add(); Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString("dd.MM.yyyy")); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally { switch (format) { case Document_Format.Word: //Сохранение документа с названием из метода, //и в формате doc document.SaveAs2(string.Format("{0}\\{1}", Environment.CurrentDirectory, name), word.WdSaveFormat.wdFormatDocument); break; case Document_Format.PDF: //Сохранение документа в формате PDF document.SaveAs2(string.Format("{0}\\{1}", Environment.CurrentDirectory, name), word.WdSaveFormat.wdFormatPDF); break; } //Закрываем документ document.Close(); //Выходим из процесса с его закрытием application.Quit(); } break; case Document_Format.Excel: //Создание процесса Excel excel.Application application_ex = new excel.Application(); //Создание книги excel.Workbook workbook = application_ex.Workbooks.Add(); //Создание страницы excel.Worksheet worksheet = (excel.Worksheet)workbook.ActiveSheet; try { switch (type) { case Document_Type.Report: //Название страницы worksheet.Name = "Отчёт"; for (int row = 0; row < table.Rows.Count; row++) { for (int col = 0; col < table.Columns.Count; col++) { //ЗАнесение данных в ячейку worksheet.Cells[row + 1][col + 1] = table.Rows[row][col].ToString(); } } //Указание диапазона работы с ячеёками листа excel.Range border //Начало диапазона = worksheet.Range[worksheet.Cells[1, 1], //Динамический конец диапазона в зависимости от //выдодимых данных worksheet.Cells[table.Rows.Count + 1] [table.Columns.Count + 1]]; //Стиль линий границ ячеек border.Borders.LineStyle = excel.XlLineStyle.xlContinuous; //Выравнивание во высоте border.VerticalAlignment = excel.XlHAlign.xlHAlignCenter; //Выравнивание по ширине border.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter; //Внесение даты создания документа worksheet.Cells[table.Rows.Count + 3][2] = string.Format("Дата создания {0}", DateTime.Now.ToString()); //Объединение ячеек worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 2]].Merge(); break; case Document_Type.Statistic: worksheet.Name = "Статистический отчёт"; for (int row = 0; row < table.Rows.Count; row++) { for (int col = 0; col < table.Columns.Count; col++) { worksheet.Cells[row + 1][col + 1] = table.Rows[row][col].ToString(); } } excel.Range border1 = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 1] [table.Columns.Count + 1]]; border1.Borders.LineStyle = excel.XlLineStyle.xlContinuous; border1.VerticalAlignment = excel.XlHAlign.xlHAlignCenter; border1.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter; worksheet.Cells[table.Rows.Count + 3][2] = string.Format("Дата создания {0}", DateTime.Now.ToString()); worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 2]].Merge(); //Класс области графиков excel.ChartObjects chartObjects = (excel.ChartObjects)worksheet.ChartObjects( Type.Missing); //Область размещения графиков: отступы слева сверху, //размер ширина и высота excel.ChartObject chartObject = chartObjects.Add(300, 50, 250, 250); //Объявление области графика excel.Chart chart = chartObject.Chart; //Объявление колекции построений графиков excel.SeriesCollection seriesCollection = (excel.SeriesCollection)chart.SeriesCollection( Type.Missing); //Объявление посторения графика excel.Series series = seriesCollection.NewSeries(); //Тип графика chart.ChartType = excel.XlChartType.xl3DColumn; //Диапазон значений по оси X series.XValues = worksheet.get_Range("B2", "B" + table.Rows.Count + 1); //Диапазон значений по оси Y series.Values = worksheet.get_Range("C2", "C" + table.Rows.Count + 1); break; } } catch { } finally { //Сохранение книги workbook.SaveAs(string.Format("{0}\\{1}", Environment.CurrentDirectory, name), application_ex.DefaultSaveFormat); //Закрытие книги workbook.Close(); //Завершение процесса application_ex.Quit(); } break; } break; case false: System.Windows.Forms.MessageBox.Show ("Введите название документа"); break; } }