From 19b9d83d7454f387625ad40fde90c647e57c4918 Mon Sep 17 00:00:00 2001 From: revengel66 Date: Mon, 28 Oct 2024 20:23:38 +0400 Subject: [PATCH] lab 2 in process --- ComponentsLibrary/ComponentBigText.cs | 67 +++++-- ComponentsLibrary/ComponentTable.cs | 193 +++++++++++-------- ComponentsLibrary/ComponentsLibrary.csproj | 1 + ComponentsLibrary/DocumentSymple.cs | 16 -- ComponentsLibrary/DocumentTable.cs | 31 --- ComponentsLibrary/TestComponent.cs | 3 +- ComponentsLibrary/entities/ColumnParams.cs | 10 + ComponentsLibrary/entities/DocumentSymple.cs | 16 ++ ComponentsLibrary/entities/DocumentTable.cs | 27 +++ ComponentsLibrary/entities/Employee.cs | 37 ++++ ComponentsView/FormComponents.Designer.cs | 20 +- ComponentsView/FormComponents.cs | 112 ++++++----- ComponentsView/FormComponents.resx | 3 + ComponentsView/Program.cs | 116 +---------- 14 files changed, 331 insertions(+), 321 deletions(-) delete mode 100644 ComponentsLibrary/DocumentSymple.cs delete mode 100644 ComponentsLibrary/DocumentTable.cs create mode 100644 ComponentsLibrary/entities/ColumnParams.cs create mode 100644 ComponentsLibrary/entities/DocumentSymple.cs create mode 100644 ComponentsLibrary/entities/DocumentTable.cs create mode 100644 ComponentsLibrary/entities/Employee.cs diff --git a/ComponentsLibrary/ComponentBigText.cs b/ComponentsLibrary/ComponentBigText.cs index 7c7da9c..a490cf6 100644 --- a/ComponentsLibrary/ComponentBigText.cs +++ b/ComponentsLibrary/ComponentBigText.cs @@ -1,4 +1,5 @@ -using DocumentFormat.OpenXml; +using ComponentsLibrary.entities; +using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.ComponentModel; @@ -6,7 +7,7 @@ using System.ComponentModel; namespace ComponentsLibrary { - public partial class ComponentBigText : Component + public partial class ComponentBigText : Component { public ComponentBigText() { @@ -16,37 +17,71 @@ namespace ComponentsLibrary public ComponentBigText(IContainer container) { container.Add(this); - InitializeComponent(); } - //публичный метод - public void SetText(string fileUrl, string fileName, string[] text) + public void CreateWordText(DocumentSymple docInfo) { - if (string.IsNullOrEmpty(fileUrl) || string.IsNullOrEmpty(fileName)) + if (string.IsNullOrEmpty(docInfo.FileUrl) || string.IsNullOrEmpty(docInfo.Title) || !CheckData(docInfo.Text)) { - throw new ArgumentException("File URL or filename cannot be empty."); + throw new Exception("Не все данные заполнены"); } - using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(Path.Combine(fileUrl, fileName), WordprocessingDocumentType.Document)) + using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(docInfo.FileUrl, WordprocessingDocumentType.Document)) { - + // Добавляем главную часть документа MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new Document(); - Body body = new Body(); + Body body = mainPart.Document.AppendChild(new Body()); + + // Создаем параграф для заголовка + Paragraph titleParagraph = new Paragraph(); + + // Задаем свойства параграфа (центровка и отступ) + ParagraphProperties paragraphProperties = new ParagraphProperties(); + paragraphProperties.AppendChild(new Justification() { Val = JustificationValues.Center }); + + // Применяем свойства параграфа к заголовку + titleParagraph.AppendChild(paragraphProperties); + + // Создаем "бегунок" текста + Run titleRun = new Run(); + + // Устанавливаем свойства "бегунка" (шрифт, размер, жирный шрифт) + RunProperties runProperties = new RunProperties(); + runProperties.AppendChild(new Bold()); + runProperties.AppendChild(new FontSize() { Val = "48" }); // Размер шрифта, 24pt + + // Применяем свойства к тексту + titleRun.AppendChild(runProperties); + + // Добавляем текст заголовка + titleRun.AppendChild(new Text(docInfo.Title)); + + // Добавляем "бегунок" с текстом в параграф + titleParagraph.AppendChild(titleRun); + + // Добавляем параграф в тело документа + body.AppendChild(titleParagraph); - foreach (var line in text) + foreach (var line in docInfo.Text) { Paragraph paragraph = new Paragraph(new Run(new Text(line))); body.Append(paragraph); } - - - mainPart.Document.Append(body); - mainPart.Document.Save(); + mainPart.Document.Save(); } - + } + + bool CheckData(string[] data) + { + for (int i = 0; i < data.Length; i++) + { + if (string.IsNullOrEmpty(data[i])) return false; + } + + return true; } } } diff --git a/ComponentsLibrary/ComponentTable.cs b/ComponentsLibrary/ComponentTable.cs index c791e8a..b0d32bf 100644 --- a/ComponentsLibrary/ComponentTable.cs +++ b/ComponentsLibrary/ComponentTable.cs @@ -1,5 +1,6 @@ -using DocumentFormat.OpenXml.Packaging; -using DocumentFormat.OpenXml.Wordprocessing; +using Aspose.Words; +using Aspose.Words.Tables; +using ComponentsLibrary.entities; using System.ComponentModel; @@ -18,94 +19,126 @@ namespace ComponentsLibrary InitializeComponent(); } - /* - public void CreateDocument(string filePath, DocumentTable documentTable) + public void CreateTable(DocumentTable tableWord) where T : class { - ValidateInput(documentTable); - - using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) + // Проверка наличия данных и определений столбцов + if (tableWord.Items == null || tableWord.Items.Count == 0 || tableWord.ColumnParameters == null || tableWord.ColumnParameters.Count == 0) { - MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); - mainPart.Document = new Document(); - Body body = new Body(); - - // Добавление заголовка - Paragraph titleParagraph = new Paragraph(new Run(new Text(documentTable.DocumentTitle))); - body.Append(titleParagraph); - - // Создание таблицы - Table table = new Table(); - CreateHeaderRows(documentTable, table); - FillTableData(documentTable, table); - - body.Append(table); - mainPart.Document.Append(body); - mainPart.Document.Save(); - } - } - - private void ValidateInput(DocumentTable documentTable) - { - // Проводим проверки на заполненность и соответствие - if (string.IsNullOrEmpty(documentTable.DocumentTitle)) - throw new ArgumentException("Заголовок документа не может быть пустым."); - - if (documentTable.Headers == null || documentTable.Headers.Count == 0 || documentTable.PropertyMappings == null || documentTable.PropertyMappings.Count == 0) - throw new ArgumentException("Заголовки и отображения свойств должны быть заполнены."); - - if (documentTable.Data == null || !documentTable.Data.Any()) - throw new ArgumentException("Данные таблицы не могут быть пустыми."); - - // Проверка на некорректные столбцы объединения - foreach (var column in documentTable.MergedColumns) - { - if (column < 0 || column >= documentTable.Headers.Count) - throw new ArgumentOutOfRangeException($"Неверный номер объединяемого столбца: {column}"); + throw new ArgumentException("Не все данные заполнены"); } - // Проверка, что все заголовки заполнены - foreach (var header in documentTable.Headers) + // Проверка, что все ячейки шапки заполнены и для каждого столбца определено свойство/поле класса + foreach (var columnParameters in tableWord.ColumnParameters) { - if (string.IsNullOrEmpty(header)) - throw new ArgumentException("Все заголовки должны быть заполнены."); - } - } - - private void CreateHeaderRows(DocumentTable documentTable, Table table) - { - // Создаем две строки заголовков - for (int rowIndex = 0; rowIndex < 2; rowIndex++) - { - TableRow headerRow = new TableRow(); - for (int colIndex = 0; colIndex < documentTable.Headers.Count; colIndex++) + if (string.IsNullOrEmpty(columnParameters.PropertyName)) { - TableCell cell = new TableCell(new Paragraph(new Run(new Text(documentTable.Headers[colIndex])))); - if (!documentTable.MergedColumns.Contains(colIndex)) + throw new ArgumentException($"Incomplete column definition: {columnParameters.FirstRowHeader}"); + } + } + + // Создание документа + Document document = new Document(); + DocumentBuilder builder = new DocumentBuilder(document); + + // Установка стиля заголовка + Style titleStyle = builder.Document.Styles.Add(StyleType.Paragraph, "Title"); + titleStyle.Font.Size = 16; + titleStyle.Font.Bold = true; + + // Установка заголовка документа + builder.ParagraphFormat.Style = titleStyle; + builder.Writeln(tableWord.Title); + + // Создание таблицы + Table table = builder.StartTable(); + + // Установка стиля для шапки таблицы + Style headerStyle = builder.Document.Styles.Add(StyleType.Paragraph, "HeaderStyle"); + headerStyle.Font.Size = 14; + headerStyle.Font.Bold = true; + + + // Создание первой строки (шапка) + foreach (var columnParameters in tableWord.ColumnParameters) + { + builder.InsertCell(); + builder.ParagraphFormat.Style = headerStyle; + builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnParameters.Width); + builder.Write(columnParameters.FirstRowHeader); + } + builder.EndRow(); + + // Создание второй строки (шапка) + foreach (var columnParameters in tableWord.ColumnParameters) + { + builder.InsertCell(); + builder.ParagraphFormat.Style = headerStyle; + builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnParameters.Width); + builder.Write(columnParameters.SecondRowHeader); + } + builder.EndRow(); + + int startCellIndex = -1; + int endCellIndex = -1; + + // Создаем набор для хранения индексов ячеек, которые уже объединены по горизонтали + HashSet horizontallyMergedCells = new(); + // Объединение ячеек в первой строке шапки таблицы (если необходимо) + foreach (var mergedColumn in tableWord.MergedColumns) + { + startCellIndex = mergedColumn[0]; + endCellIndex = mergedColumn[^1]; + + for (int i = startCellIndex; i <= endCellIndex; i++) + { + // Устанавливаем горизонтальное объединение + table.Rows[0].Cells[i].CellFormat.HorizontalMerge = i == startCellIndex ? CellMerge.First : CellMerge.Previous; + horizontallyMergedCells.Add(i); // Сохраняем индекс ячейки, которая объединена по горизонтали + + // Устанавливаем выравнивание по центру + if (i == startCellIndex) { - // Объединяем ячейку по строкам - cell.VerticalMerge = new TableCellVerticalMerge(); + // Центрируем текст внутри ячейки + table.Rows[0].Cells[i].Paragraphs[0].ParagraphFormat.Alignment = ParagraphAlignment.Center; } - - headerRow.Append(cell); } - table.Append(headerRow); } + + // Установка вертикального объединения заголовков + for (int columnIndex = 0; columnIndex < tableWord.ColumnParameters.Count; columnIndex++) + { + // Пропускаем столбцы, которые уже объединены по горизонтали + if (horizontallyMergedCells.Contains(columnIndex)) + continue; + + table.Rows[0].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.First; + table.Rows[1].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.Previous; + } + + // Установка стиля для данных таблицы + Style dataStyle = builder.Document.Styles.Add(StyleType.Paragraph, "DataStyle"); + dataStyle.Font.Size = 12; + dataStyle.Font.Bold = false; + + // Вставка данных в таблицу + foreach (var item in tableWord.Items) + { + foreach (var сolumnParameters in tableWord.ColumnParameters) + { + builder.InsertCell(); + builder.ParagraphFormat.Style = dataStyle; + // Получение значения свойства/поля объекта по заданному имени + var propertyValue = item.GetType().GetProperty(сolumnParameters.PropertyName)?.GetValue(item)?.ToString(); + builder.Write(propertyValue ?? string.Empty); + } + builder.EndRow(); + } + + builder.EndTable(); + + // Сохранение документа в файл + document.Save(tableWord.FileUrl); } - private void FillTableData(DocumentTable documentTable, Table table) - { - // Заполнение данных таблицы - foreach (var item in documentTable.Data) - { - TableRow dataRow = new TableRow(); - for (int colIndex = 0; colIndex < documentTable.PropertyMappings.Count; colIndex++) - { - var propertyValue = typeof(T).GetProperty(documentTable.PropertyMappings[colIndex])?.GetValue(item, null); - TableCell cell = new TableCell(new Paragraph(new Run(new Text(propertyValue?.ToString() ?? string.Empty)))); - dataRow.Append(cell); - } - table.Append(dataRow); - } - }*/ - } + } } diff --git a/ComponentsLibrary/ComponentsLibrary.csproj b/ComponentsLibrary/ComponentsLibrary.csproj index abce47b..916883a 100644 --- a/ComponentsLibrary/ComponentsLibrary.csproj +++ b/ComponentsLibrary/ComponentsLibrary.csproj @@ -8,6 +8,7 @@ + diff --git a/ComponentsLibrary/DocumentSymple.cs b/ComponentsLibrary/DocumentSymple.cs deleted file mode 100644 index 4459fde..0000000 --- a/ComponentsLibrary/DocumentSymple.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace ComponentsView -{ - public class DocumentSymple - { - public string FileUrl { get; set; } = string.Empty; - public string FileName { get; set; } = string.Empty; - public string[] Text { get; set; } - - public DocumentSymple(string fileUrl, string fileName, string[] text) - { - FileUrl = fileUrl; - FileName = fileName; - Text = text; - } - } -} diff --git a/ComponentsLibrary/DocumentTable.cs b/ComponentsLibrary/DocumentTable.cs deleted file mode 100644 index 76bf39e..0000000 --- a/ComponentsLibrary/DocumentTable.cs +++ /dev/null @@ -1,31 +0,0 @@ - -namespace ComponentsLibrary -{ - public class DocumentTable - { - public string DocumentTitle { get; set; } = string.Empty; - public string DocumentPath { get; set; } = string.Empty; - public List MergedColumns { get; set; } - public List ColumnWidths { get; set; } - public List Headers { get; set; } - public List Data { get; set; } - public List PropertyMappings { get; set; } - - public DocumentTable(string documentTitle, - string documentPath, - List mergedColumns, - List columnWidths, - List headers, - List data, - List propertyMappings) - { - DocumentTitle = documentTitle; - DocumentPath = documentPath; - MergedColumns = mergedColumns; - ColumnWidths = columnWidths; - Headers = headers; - Data = data; - PropertyMappings = propertyMappings; - } - } -} diff --git a/ComponentsLibrary/TestComponent.cs b/ComponentsLibrary/TestComponent.cs index 0bc7f3a..145939b 100644 --- a/ComponentsLibrary/TestComponent.cs +++ b/ComponentsLibrary/TestComponent.cs @@ -1,5 +1,4 @@ -using ComponentsView; -using System.ComponentModel; +using System.ComponentModel; using static System.Net.Mime.MediaTypeNames; namespace ComponentsLibrary diff --git a/ComponentsLibrary/entities/ColumnParams.cs b/ComponentsLibrary/entities/ColumnParams.cs new file mode 100644 index 0000000..b77707a --- /dev/null +++ b/ComponentsLibrary/entities/ColumnParams.cs @@ -0,0 +1,10 @@ +namespace ComponentsLibrary.entities +{ + public class ColumnParams + { + public string FirstRowHeader { get; set; } = string.Empty; + public string SecondRowHeader { get; set; } = string.Empty; + public string PropertyName { get; set; } = string.Empty; + public double Width { get; set; } + } +} diff --git a/ComponentsLibrary/entities/DocumentSymple.cs b/ComponentsLibrary/entities/DocumentSymple.cs new file mode 100644 index 0000000..4edf132 --- /dev/null +++ b/ComponentsLibrary/entities/DocumentSymple.cs @@ -0,0 +1,16 @@ +namespace ComponentsLibrary.entities +{ + public class DocumentSymple + { + public string FileUrl { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public string[] Text { get; set; } + + public DocumentSymple(string fileUrl, string title, string[] text) + { + FileUrl = fileUrl; + Title = title; + Text = text; + } + } +} diff --git a/ComponentsLibrary/entities/DocumentTable.cs b/ComponentsLibrary/entities/DocumentTable.cs new file mode 100644 index 0000000..ca0804e --- /dev/null +++ b/ComponentsLibrary/entities/DocumentTable.cs @@ -0,0 +1,27 @@ +namespace ComponentsLibrary.entities +{ + public class DocumentTable + { + //путь до файла + public string FileUrl { get; set; } = string.Empty; + //заголовок в документе + public string Title { get; set; } = string.Empty; + //параметры колонок (ширина и тд) + public List ColumnParameters { get; set; } = new(); + + //данные для таблицы + public List Items { get; set; } = new(); + + //информация по объединению колонок + public List MergedColumns { get; set; } = new(); + + public DocumentTable(string fileUrl, string title, List columnParameters, List data, List mergedColumns) + { + FileUrl = fileUrl; + Title = title; + ColumnParameters = columnParameters; + Items = data; + MergedColumns = mergedColumns; + } + } +} diff --git a/ComponentsLibrary/entities/Employee.cs b/ComponentsLibrary/entities/Employee.cs new file mode 100644 index 0000000..76eaa55 --- /dev/null +++ b/ComponentsLibrary/entities/Employee.cs @@ -0,0 +1,37 @@ +namespace ComponentsLibrary.entities +{ + public class Employee + { + public string Status { get; set; } + public string Name { get; set; } + public string Surname { get; set; } + public string Age { get; set; } + public string Childrens { get; set; } + public string Car { get; set; } + public string Post { get; set; } + public string Experience { get; set; } + public string Prize { get; set; } + + + public Employee(string status, string name, string surname, string age,string childrens,string car,string post,string experience,string prize) + { + Status = status; + Name = name; + Surname = surname; + Age = age; + Childrens = childrens; + Car = car; + Post = post; + Experience = experience; + Prize = prize; + } + + public Employee() { } + + public override string ToString() + { + string temp = Status + ", " + Name + ", " + Surname + ", " + Age + ", " + Childrens + ", " + Car + ", " + Post + ", " + Experience + ", " + Prize; + return temp; + } + } +} diff --git a/ComponentsView/FormComponents.Designer.cs b/ComponentsView/FormComponents.Designer.cs index 319fdbd..1e1e18c 100644 --- a/ComponentsView/FormComponents.Designer.cs +++ b/ComponentsView/FormComponents.Designer.cs @@ -36,9 +36,7 @@ richTextBoxWord = new RichTextBox(); buttonSaveTextWord = new Button(); componentTable = new ComponentsLibrary.ComponentTable(components); - dataGridViewTable = new DataGridView(); buttonSaveTable = new Button(); - ((System.ComponentModel.ISupportInitialize)dataGridViewTable).BeginInit(); SuspendLayout(); // // richTextBoxTest @@ -77,22 +75,13 @@ buttonSaveTextWord.UseVisualStyleBackColor = true; buttonSaveTextWord.Click += buttonSaveTextWord_Click; // - // dataGridViewTable - // - dataGridViewTable.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridViewTable.Location = new Point(12, 143); - dataGridViewTable.Name = "dataGridViewTable"; - dataGridViewTable.RowTemplate.Height = 25; - dataGridViewTable.Size = new Size(350, 167); - dataGridViewTable.TabIndex = 4; - // // buttonSaveTable // - buttonSaveTable.Location = new Point(12, 316); + buttonSaveTable.Location = new Point(12, 143); buttonSaveTable.Name = "buttonSaveTable"; - buttonSaveTable.Size = new Size(350, 23); + buttonSaveTable.Size = new Size(350, 41); buttonSaveTable.TabIndex = 5; - buttonSaveTable.Text = "Сохранить"; + buttonSaveTable.Text = "Cоздать документ с таблицей"; buttonSaveTable.UseVisualStyleBackColor = true; buttonSaveTable.Click += buttonSaveTable_Click; // @@ -102,14 +91,12 @@ AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(800, 450); Controls.Add(buttonSaveTable); - Controls.Add(dataGridViewTable); Controls.Add(buttonSaveTextWord); Controls.Add(richTextBoxWord); Controls.Add(buttonSaveText); Controls.Add(richTextBoxTest); Name = "FormComponents"; Text = "Form1"; - ((System.ComponentModel.ISupportInitialize)dataGridViewTable).EndInit(); ResumeLayout(false); } @@ -122,7 +109,6 @@ private RichTextBox richTextBoxWord; private Button buttonSaveTextWord; private ComponentsLibrary.ComponentTable componentTable; - private DataGridView dataGridViewTable; private Button buttonSaveTable; } } diff --git a/ComponentsView/FormComponents.cs b/ComponentsView/FormComponents.cs index 800b1be..d26f717 100644 --- a/ComponentsView/FormComponents.cs +++ b/ComponentsView/FormComponents.cs @@ -1,4 +1,5 @@ using System.Windows.Forms; +using ComponentsLibrary.entities; namespace ComponentsView { @@ -8,7 +9,6 @@ namespace ComponentsView { InitializeComponent(); testComponent.FileName = "2.txt"; - InitializeDataGridView(); } private void buttonSaveText_Click(object sender, EventArgs e) @@ -29,62 +29,84 @@ namespace ComponentsView private void buttonSaveTextWord_Click(object sender, EventArgs e) { - try + using var dialog = new SaveFileDialog { - var docEntry = new DocumentSymple(@"\5semestr\KOP\KOP-PIbd-32-Katysheva-N-E\docs", "Word.docx", richTextBoxWord.Lines); - componentBigText.SetText(docEntry.FileUrl, docEntry.FileName, docEntry.Text); - MessageBox.Show(" ", "", - MessageBoxButtons.OK, MessageBoxIcon.Information); - } - catch (Exception ex) + Filter = "docx|*.docx" + }; + if (dialog.ShowDialog() == DialogResult.OK) { - MessageBox.Show(ex.Message, "!", - MessageBoxButtons.OK, MessageBoxIcon.Error); + try + { + DocumentSymple doc = new(dialog.FileName, "- ?", richTextBoxWord.Lines); + componentBigText.CreateWordText(doc); + MessageBox.Show(" ", "", + MessageBoxButtons.OK, MessageBoxIcon.Information); + } + + catch (Exception ex) + { + MessageBox.Show(ex.Message, "!", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } - private void InitializeDataGridView() - { - dataGridViewTable.Columns.Add("Column1", ""); - dataGridViewTable.Columns.Add("Column2", ""); - dataGridViewTable.Columns.Add("Column3", " "); - dataGridViewTable.Rows.Add("1", "1","2 1"); - dataGridViewTable.Rows.Add("2", "2", "2 2"); - dataGridViewTable.Rows.Add("3", "3", "2 3"); - dataGridViewTable.Rows.Add("4", "4", "2 4"); - dataGridViewTable.Rows.Add("5", "5", "2 5"); - dataGridViewTable.Rows.Add("6", "6", "2 6"); - } - private void buttonSaveTable_Click(object sender, EventArgs e) { - try + List mergedColumns = new() { - List data = new List(); + new int[] { 1, 5 }, + new int[] { 6, 7 }, + }; - // DataGridView - foreach (DataGridViewRow row in dataGridViewTable.Rows) + var columns = new List + { + new() { FirstRowHeader = "", SecondRowHeader = "", PropertyName = "Status", Width = 1 }, + new() { FirstRowHeader = " ", SecondRowHeader = "",PropertyName = "Name", Width = 1 }, + new() { FirstRowHeader = " ", SecondRowHeader = "", PropertyName = "Surname", Width = 1 }, + new() { FirstRowHeader = " ", SecondRowHeader = "", PropertyName = "Age", Width = 0.1 }, + new() { FirstRowHeader = " ", SecondRowHeader = "", PropertyName = "Childrens", Width = 0.1 }, + new() { FirstRowHeader = " ", SecondRowHeader = "", PropertyName = "Car", Width = 1 }, + new() { FirstRowHeader = "", SecondRowHeader = "", PropertyName = "Post", Width = 1 }, + new() { FirstRowHeader = "", SecondRowHeader = "", PropertyName = "Experience", Width = 1 }, + new() { FirstRowHeader = "", SecondRowHeader = "", PropertyName = "Prize", Width = 1 }, + }; + + var employees = new List + { + new() { Status = "Active", Name = "John", Surname = "Doe", Age = "35", Childrens = "2", Car = "Toyota", Post = "Manager", Experience = "10 years", Prize = "5000" }, + new() { Status = "On Leave", Name = "Alice", Surname = "Smith", Age = "28", Childrens = "1", Car = "Honda", Post = "Developer", Experience = "5 years", Prize = "3000" }, + new() { Status = "Active", Name = "Bob", Surname = "Brown", Age = "40", Childrens = "3", Car = "Ford", Post = "Team Lead", Experience = "15 years", Prize = "7000" }, + new() { Status = "Retired", Name = "Carol", Surname = "Johnson", Age = "65", Childrens = "4", Car = "None", Post = "Accountant", Experience = "30 years", Prize = "10000" }, + new() { Status = "Active", Name = "David", Surname = "Wilson", Age = "45", Childrens = "2", Car = "Chevrolet", Post = "Designer", Experience = "20 years", Prize = "4000" }, + new() { Status = "Active", Name = "Eve", Surname = "Davis", Age = "32", Childrens = "0", Car = "Tesla", Post = "Data Scientist", Experience = "8 years", Prize = "6000" }, + new() { Status = "On Leave", Name = "Frank", Surname = "Miller", Age = "38", Childrens = "2", Car = "BMW", Post = "Product Manager", Experience = "12 years", Prize = "5500" }, + new() { Status = "Active", Name = "Grace", Surname = "Taylor", Age = "29", Childrens = "1", Car = "Mercedes", Post = "QA Engineer", Experience = "6 years", Prize = "3500" }, + new() { Status = "Resigned", Name = "Henry", Surname = "Anderson", Age = "50", Childrens = "3", Car = "Audi", Post = "CTO", Experience = "25 years", Prize = "12000" }, + new() { Status = "Active", Name = "Ivy", Surname = "Thomas", Age = "27", Childrens = "0", Car = "Volkswagen", Post = "Intern", Experience = "1 year", Prize = "1000" } + }; + + + using var dialog = new SaveFileDialog + { + Filter = "docx|*.docx" + }; + + if (dialog.ShowDialog() == DialogResult.OK) + { + try { - if (row.IsNewRow) continue; // - string[] rowData = new string[dataGridViewTable.Columns.Count]; - for (int i = 0; i < dataGridViewTable.Columns.Count; i++) - { - rowData[i] = row.Cells[i].Value?.ToString() ?? string.Empty; - } - data.Add(rowData); + DocumentTable info = new(dialog.FileName, " 2", columns, employees, mergedColumns); + componentTable.CreateTable(info); + + MessageBox.Show(" ", "", + MessageBoxButtons.OK, MessageBoxIcon.Information); } - - // - var docEntry = new DocumentSymple(@"\5semestr\KOP\KOP-PIbd-32-Katysheva-N-E\docs", "Table.docx", data.Select(row => string.Join("\t", row)).ToArray()); - componentBigText.SetText(docEntry.FileUrl, docEntry.FileName, docEntry.Text); - - MessageBox.Show(" ", "", - MessageBoxButtons.OK, MessageBoxIcon.Information); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "!", + catch (Exception ex) + { + MessageBox.Show(ex.Message, "!", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } } diff --git a/ComponentsView/FormComponents.resx b/ComponentsView/FormComponents.resx index 2bef43e..416d8db 100644 --- a/ComponentsView/FormComponents.resx +++ b/ComponentsView/FormComponents.resx @@ -126,4 +126,7 @@ 308, 17 + + 451, 17 + \ No newline at end of file diff --git a/ComponentsView/Program.cs b/ComponentsView/Program.cs index 9b56f5e..79ad944 100644 --- a/ComponentsView/Program.cs +++ b/ComponentsView/Program.cs @@ -13,120 +13,8 @@ namespace ComponentsView { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. - //ApplicationConfiguration.Initialize(); - //Application.Run(new FormComponents()); - - const string fileName = @"AddTable.docx"; - const string fileUrl = @"\5semestr\KOP\KOP-PIbd-32-Katysheva-N-E"; - AddTable(); - - static void AddTable() { - - - using (WordprocessingDocument document = WordprocessingDocument.Create(Path.Combine(fileUrl, fileName), WordprocessingDocumentType.Document)) - { - - //var doc = document.MainDocumentPart.Document; - MainDocumentPart mainPart = document.AddMainDocumentPart(); - mainPart.Document = new Document(); - Body body = new Body(); - - Table table = new Table(); - - TableProperties props = new TableProperties( - new TableBorders( - new TopBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new BottomBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new LeftBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new RightBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new InsideHorizontalBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - }, - new InsideVerticalBorder - { - Val = new EnumValue(BorderValues.Single), - Size = 12 - } - ) - ); - table.AppendChild(props); - - var headerRow = new TableRow(); - for (var j = 0; j <= 3; j++) - { - var tc = new TableCell(); - - - - TableCellProperties cellProps = new TableCellProperties(); - TableCellWidth cellWidth = new TableCellWidth() { Type = TableWidthUnitValues.Auto }; - cellProps.Append(cellWidth); - - if (j == 0) - { - GridSpan gridSpan = new GridSpan() { Val = 3 }; - cellProps.Append(gridSpan); - } - if (j == 1 || j == 2) - { - continue; - } - - RunProperties headerRunProperties = new RunProperties(); - Bold bold = new Bold(); - headerRunProperties.Append(bold); - - string headerText = "Column " + j; - Run run = new Run(new Text(headerText)); - run.PrependChild(headerRunProperties); - - - tc.Append(new Paragraph(run)); - tc.Append(cellProps); - headerRow.Append(tc); - } - table.Append(headerRow); - - for (var i = 0; i <= 3; i++) - { - var tr = new TableRow(); - for (var j = 0; j <= 3; j++) - { - var tc = new TableCell(); - string data = "info" + i; - tc.Append(new Paragraph(new Run(new Text(data)))); - tc.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Auto })); - tr.Append(tc); - } - table.Append(tr); - } - - body.Append(table); - - mainPart.Document.Append(body); - mainPart.Document.Save(); - - } - } - + ApplicationConfiguration.Initialize(); + Application.Run(new FormComponents()); } } } \ No newline at end of file