public void Export_Data_To_Word(DataGridView DGV, string filename) { try { object missing = System.Reflection.Missing.Value; if (DGV.Rows.Count != 0) { int RowCount = DGV.Rows.Count; int ColumnCount = DGV.Columns.Count; Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1]; int r = 0; //add rows for (int c = 0; c <= ColumnCount - 1; c++) { for (r = 0; r <= RowCount - 1; r++) { DataArray[r, c] = DGV.Rows[r].Cells[c].Value; } //end row loop } //end column loop Word.Document oDoc = new Word.Document(); //page orintation oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; dynamic oRange = oDoc.Content.Application.Selection.Range; string oTemp = ""; for (r = 0; r <= RowCount - 1; r++) { for (int c = 0; c <= ColumnCount - 1; c++) { oTemp = oTemp + DataArray[r, c]?.ToString().Replace("\t", "").Replace("\n", "") .Replace("\r", "") + "\t"; } } //table format oRange.Text = oTemp; object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs; object ApplyBorders = true; object AutoFit = true; object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent; oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount, Type.Missing, Type.Missing, ref ApplyBorders, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing); oRange.Select(); oDoc.Application.Selection.Tables[1].Select(); oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0; oDoc.Application.Selection.Tables[1].Rows.Alignment = 0; oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.InsertRowsAbove(1); oDoc.Application.Selection.Tables[1].Rows[1].Select(); //header row style oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma"; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14; //add header row manually for (int c = 0; c <= ColumnCount - 1; c++) { oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText; } //table style //oDoc.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5"); oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; oDoc.Application.Selection.Tables[1].Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; oDoc.Application.Selection.Tables[1].Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; //header text foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.Text = "Результаты"; headerRange.Font.Size = 16; headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } //save the file oDoc.SaveAs2000(filename); oDoc.Application.Documents[filename].Save(); oDoc.Close(ref missing, ref missing, ref missing); //NASSIM LOUCHANI } } catch (Exception e) { MessageBox.Show(e.Message, @"Есть несохраненные результаты!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void ExportToWord(string SaveTrack) { //тестовый блок /*this.inform.ClassNum = 3; * this.inform.Comand = "к неполной разборке автомата приступить!"; * this.inform.Decreace = "потеря автомата - ссылка в дизбад"; * this.inform.Literature = "Учебник \"Военная топография\", стр 94-95"; * this.inform.Material = "Топографические карты. Клей. Ножницы (нож). Карандаши. Офицерские линейки. Курвиметры. Клей."; * this.inform.Place = "класс"; * this.inform.Purpose = "привить навык по разборке оружия"; * this.inform.Time = 90; * this.inform.Topic = "Сборка и разборка оружия";*/ //конец тестового блока WordProgress progress = new WordProgress(); progress.ProgressBarForm(((this.tasks.Count + 1) * 5) + 21); progress.label2.Text = SaveTrack + @"\" + this.Inform.Course + " " + this.inform.Name + ".doc"; progress.Show(); //открытие приложения Word app = new Word.Application(); app.Visible = false; progress.ProgressBarInc(); //создание нового документа Word doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing); progress.ProgressBarInc(); doc.PageSetup.TopMargin = 35; doc.PageSetup.RightMargin = 35; doc.PageSetup.BottomMargin = 35; doc.PageSetup.LeftMargin = 35; object oStart = doc.Content.Start; object oEnd = doc.Content.End; Word.Range docRange = doc.Range(ref oStart, ref oEnd); docRange.Font.Name = "Times New Roman"; doc.Paragraphs.SpaceAfter = 0; progress.ProgressBarInc(); //блок титульного листа1 //строка "Карточка задания" this.PrintPar("КАРТОЧКА ЗАДАНИЯ", 1, false); progress.ProgressBarInc(); //Строка с названием предмета this.PrintPar(this.inform.Course, 1, false); progress.ProgressBarInc(); //Строка с номером и темой занятия this.PrintPar("Занятие №" + this.inform.ClassNum + " \"" + this.inform.Topic + "\"", 1, true); progress.ProgressBarInc(); //Строка с названием карточки задания this.PrintPar("\"" + this.inform.Name + "\"", 1, false); progress.ProgressBarInc(); //блок титульного листа2 //Строка с целью занятия this.PrintPar("\nЦель: " + this.inform.Purpose, 0, true); progress.ProgressBarInc(); //Строка с временем занятия this.PrintPar("Время: " + this.inform.Time + " мин.", 0, true); progress.ProgressBarInc(); //Строка с местом проведения занятия this.PrintPar("Место: " + this.inform.Place, 0, true); progress.ProgressBarInc(); //Строка с материальным обеспечением занятия this.PrintPar("Материальное обеспечение: " + this.inform.Material, 0, true); progress.ProgressBarInc(); //Строка с литературой this.PrintPar("Литература: " + this.inform.Literature, 0, true); progress.ProgressBarInc(); //Блок титульного листа 3 //Строка команды к началу действий this.PrintPar("\nНачало по команде: \"" + this.inform.Comand + "\"", 0, true); progress.ProgressBarInc(); //Строка с критериями оценки this.PrintPar("Критерии оценки: Отлично - " + this.notes.Excellent + " c, Хорошо - " + this.notes.Good + " c, Удовлетворительно - " + this.notes.Satisfactory + " с.", 0, true); progress.ProgressBarInc(); //Строка с критериями снижения оценки this.PrintPar("Оценка снижается: " + this.inform.Decreace, 0, true); progress.ProgressBarInc(); //Создание таблицы Word.Paragraph p = doc.Content.Paragraphs.Add(ref missing); var table = doc.Tables.Add(p.Range, this.Tasks.Count + 5, 5, ref missing, ref missing); table.Borders.Enable = 1; table.Columns[1].Width = 30; table.Columns[2].Width = 75; table.Columns[3].Width = 165; table.Columns[4].Width = 165; table.Columns[5].Width = 75; progress.ProgressBarInc(); Word.Cell cell; //Заполнение заголовков таблицы for (int i = 1; i <= 5; i++) { cell = table.Cell(1, i); string sname = ""; switch (i) { case 1: sname = "№"; break; case 2: sname = "Название действия"; break; case 3: sname = "Порядок выполнения"; break; case 4: sname = "Контроль"; break; case 5: sname = "Выполнено"; break; } cell.Range.Text = sname; cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25; cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; cell.Range.Font.Bold = 1; cell.Range.Font.Size = 12; progress.ProgressBarInc(); } //Запись листа в таблицу for (int i = 0; i < this.Tasks.Count; i++) { for (int j = 1; j <= 5; j++) { cell = table.Cell(i + 2, j); cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify; cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.Font.Size = 11; switch (j) { case 1: { cell.Range.Text = "" + (i + 1); cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25; cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; cell.Range.Font.Bold = 1; cell.Range.Font.Size = 12; } break; case 2: cell.Range.Text = this.Tasks[i].Name; break; case 3: cell.Range.Text = this.Tasks[i].Description; break; case 4: { if (this.Tasks[i].Image != null) { try { Rename(DataChekList.SaveTrack + @"\" + /*Application.StartupPath +*/ @"\CheckList\Pictures\" + this.Tasks[i].Image, true); cell.Range.InlineShapes.AddPicture(DataChekList.SaveTrack + @"\" + /*Application.StartupPath +*/ @"\CheckList\Pictures\" + string.Concat(this.Tasks[i].Image.Remove(this.Tasks[i].Image.LastIndexOf('.')), ".jpeg")); Rename(DataChekList.SaveTrack + @"\" + /*Application.StartupPath +*/ @"\CheckList\Pictures\" + string.Concat(this.Tasks[i].Image.Remove(this.Tasks[i].Image.LastIndexOf('.')), ".jpeg"), false); cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } catch (Exception e) { MessageBox.Show(e.Message); } } } break; case 5: { var box = cell.Tables.Add(cell.Range, 1, 1, ref missing, ref missing); box.Borders.Enable = 1; box.Columns[1].Width = 15; box.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter; } break; } progress.ProgressBarInc(); } } //Вставка поля с оценкой for (int i = 0; i < 4; i++) { cell = table.Cell(table.Rows.Count - i, 1); cell.Merge(table.Cell(table.Rows.Count - i, 4)); switch (i) { case 0: cell.Range.Text = "Итоговая оценка: "; break; case 1: cell.Range.Text = "Оценка снижена на количество баллов: "; break; case 2: cell.Range.Text = "Время выполнения: "; break; case 3: cell.Range.Text = "Процент выполнения: "; break; } cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; cell.Range.Font.Size = 14; cell.Range.Font.Bold = 1; progress.ProgressBarInc(); } //Сохранение файла try { doc.SaveAs2000(SaveTrack + @"\" + this.Inform.Course + " " + this.inform.Name + ".doc"); progress.ProgressBarInc(); doc.Close(ref missing, ref missing, ref missing); doc = null; app.Quit(ref missing, ref missing, ref missing); app = null; progress.ProgressBarInc(); } catch (Exception e) { MessageBox.Show(e.Message); } progress.Visible = false; }
public static void createDoc(Test test) { object missing = System.Reflection.Missing.Value; WordSaver ws = new WordSaver(); SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Word Documents (*.docx)|*.docx"; sfd.FileName = "Тест " + test.TestName + ".docx"; if (sfd.ShowDialog() == DialogResult.OK) { Word.Document doc = null; try { // Создаём объект приложения Word.Application app = new Word.Application(); // Путь до шаблона документа File.Delete(Environment.CurrentDirectory + @"\Word\" + test.TestName + ".docx"); File.Copy(Environment.CurrentDirectory + @"\Word\WordTest.docx", Environment.CurrentDirectory + @"\Word\" + test.TestName + ".docx"); string source = Environment.CurrentDirectory + @"\Word\" + test.TestName + ".docx"; // Открываем doc = app.Documents.Open(source); doc.Activate(); // Добавляем информацию // wBookmarks содержит все закладки Word.Bookmarks wBookmarks = doc.Bookmarks; //string[] data = new string[3] { "27", "Alex", "Gulynin" }; foreach (Word.Bookmark mark in wBookmarks) { if (mark.Name == "testName") { mark.Range.Text = test.TestName; } if (mark.Name == "markExcellent") { mark.Range.Text = test.ListMarks[0].ToString(); } if (mark.Name == "markGood") { mark.Range.Text = test.ListMarks[1].ToString(); } if (mark.Name == "markSatisfactory") { mark.Range.Text = test.ListMarks[2].ToString(); } if (mark.Name == "tasksStartHere") { string textForInsert = ""; int count = 0; foreach (KeyValuePair <LinkLabel, PanelWrapper> keyValue in test.ListPanelsTasks) { string taskUslovie = ""; List <TextBox> bufListTB = new List <TextBox> { }; //List<PictureBox> listPB = new List<PictureBox> { }; textForInsert += "\n\n\n\nЗадание №" + (count + 1) + "\n"; for (int i = 0; i < keyValue.Value.Entity.Controls[0].Controls.Count; i++) { if (keyValue.Value.Entity.Controls[0].Controls[i] is RichTextBox) { taskUslovie = keyValue.Value.Entity.Controls[0].Controls[i].Text; } } textForInsert += "Условие: " + taskUslovie + "\n"; for (int i = 0; i < keyValue.Value.Entity.Controls[0].Controls.Count; i++) { if (keyValue.Value.Entity.Controls[0].Controls[i] is PictureBox) { Clipboard.SetImage( ((PictureBox)(keyValue.Value.Entity.Controls[0].Controls[i])) .Image); mark.Range.Paste(); } } for (int i = keyValue.Value.Entity.Controls[0].Controls.Count; i > 0; i--) { if (keyValue.Value.Entity.Controls[0].Controls[i - 1] is TextBox) { bufListTB.Add((TextBox)keyValue.Value.Entity.Controls[0].Controls[i - 1]); } } for (int i = 0; i < bufListTB.Count; i++) { textForInsert += "Ответ №" + (i + 1) + ": "; textForInsert += bufListTB[i].Text + "\n"; } count++; } mark.Range.Text = textForInsert; } } doc.SaveAs2000(sfd.FileName); File.Delete(source); // Закрываем документ doc.Close(/*ref missing, ref missing, ref missing*/); } catch (IOException e) { MessageBox.Show("Не удалось сохранить файл, возможно он уже существует " + e.Message, @"Есть несохраненные результаты!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }