diff --git a/ComponentsLibrary/ComponentBigText.cs b/ComponentsLibrary/ComponentBigText.cs index b4b4fff..7c7da9c 100644 --- a/ComponentsLibrary/ComponentBigText.cs +++ b/ComponentsLibrary/ComponentBigText.cs @@ -1,9 +1,7 @@ -using ComponentsView; +using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; using System.ComponentModel; -using System.Reflection.Metadata; -using static System.Net.Mime.MediaTypeNames; -using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab; namespace ComponentsLibrary @@ -25,25 +23,28 @@ namespace ComponentsLibrary //публичный метод public void SetText(string fileUrl, string fileName, string[] text) { + if (string.IsNullOrEmpty(fileUrl) || string.IsNullOrEmpty(fileName)) + { + throw new ArgumentException("File URL or filename cannot be empty."); + } - // Создаем новый документ Word и сохраняем его по указанному пути using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(Path.Combine(fileUrl, fileName), WordprocessingDocumentType.Document)) { - // Добавляем главный документ + MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = new Body(); - // Добавляем текст в документ + foreach (var line in text) { Paragraph paragraph = new Paragraph(new Run(new Text(line))); body.Append(paragraph); } - // Заключаем тело документа + mainPart.Document.Append(body); - mainPart.Document.Save(); // Сохраняем изменения в документе + mainPart.Document.Save(); } } diff --git a/ComponentsLibrary/ComponentTable.Designer.cs b/ComponentsLibrary/ComponentTable.Designer.cs new file mode 100644 index 0000000..2f2c2c9 --- /dev/null +++ b/ComponentsLibrary/ComponentTable.Designer.cs @@ -0,0 +1,36 @@ +namespace ComponentsLibrary +{ + partial class ComponentTable + { + /// + /// Обязательная переменная конструктора. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} diff --git a/ComponentsLibrary/ComponentTable.cs b/ComponentsLibrary/ComponentTable.cs new file mode 100644 index 0000000..83da694 --- /dev/null +++ b/ComponentsLibrary/ComponentTable.cs @@ -0,0 +1,111 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using System.ComponentModel; + + +namespace ComponentsLibrary +{ + public partial class ComponentTable : Component + { + public ComponentTable() + { + InitializeComponent(); + } + + public ComponentTable(IContainer container) + { + container.Add(this); + + InitializeComponent(); + } + + public void CreateDocument(string filePath, DocumentTable documentTable) + { + ValidateInput(documentTable); + + using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) + { + 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}"); + } + + // Проверка, что все заголовки заполнены + foreach (var header in documentTable.Headers) + { + 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++) + { + TableCell cell = new TableCell(new Paragraph(new Run(new Text(documentTable.Headers[colIndex])))); + if (!documentTable.MergedColumns.Contains(colIndex)) + { + // Объединяем ячейку по строкам + cell.VerticalMerge = new TableCellVerticalMerge(); + } + + headerRow.Append(cell); + } + table.Append(headerRow); + } + } + + 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 060aa1c..abce47b 100644 --- a/ComponentsLibrary/ComponentsLibrary.csproj +++ b/ComponentsLibrary/ComponentsLibrary.csproj @@ -7,4 +7,8 @@ enable + + + + diff --git a/ComponentsLibrary/DocumentEntry.cs b/ComponentsLibrary/DocumentSymple.cs similarity index 71% rename from ComponentsLibrary/DocumentEntry.cs rename to ComponentsLibrary/DocumentSymple.cs index 0b6350e..4459fde 100644 --- a/ComponentsLibrary/DocumentEntry.cs +++ b/ComponentsLibrary/DocumentSymple.cs @@ -1,12 +1,12 @@ namespace ComponentsView { - public class DocumentEntry + public class DocumentSymple { public string FileUrl { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty; public string[] Text { get; set; } - public DocumentEntry(string fileUrl, string fileName, string[] text) + public DocumentSymple(string fileUrl, string fileName, string[] text) { FileUrl = fileUrl; FileName = fileName; diff --git a/ComponentsLibrary/DocumentTable.cs b/ComponentsLibrary/DocumentTable.cs new file mode 100644 index 0000000..76bf39e --- /dev/null +++ b/ComponentsLibrary/DocumentTable.cs @@ -0,0 +1,31 @@ + +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/ComponentsView/FormComponents.Designer.cs b/ComponentsView/FormComponents.Designer.cs index a3a33d3..319fdbd 100644 --- a/ComponentsView/FormComponents.Designer.cs +++ b/ComponentsView/FormComponents.Designer.cs @@ -35,6 +35,10 @@ componentBigText = new ComponentsLibrary.ComponentBigText(components); richTextBoxWord = new RichTextBox(); buttonSaveTextWord = new Button(); + componentTable = new ComponentsLibrary.ComponentTable(components); + dataGridViewTable = new DataGridView(); + buttonSaveTable = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridViewTable).BeginInit(); SuspendLayout(); // // richTextBoxTest @@ -73,17 +77,39 @@ 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.Name = "buttonSaveTable"; + buttonSaveTable.Size = new Size(350, 23); + buttonSaveTable.TabIndex = 5; + buttonSaveTable.Text = "Сохранить"; + buttonSaveTable.UseVisualStyleBackColor = true; + buttonSaveTable.Click += buttonSaveTable_Click; + // // FormComponents // AutoScaleDimensions = new SizeF(7F, 15F); 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); } @@ -95,5 +121,8 @@ private ComponentsLibrary.ComponentBigText componentBigText; 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 a2f328b..4549d4a 100644 --- a/ComponentsView/FormComponents.cs +++ b/ComponentsView/FormComponents.cs @@ -1,12 +1,14 @@ +using System.Windows.Forms; + namespace ComponentsView { public partial class FormComponents : Form { - public FormComponents() { InitializeComponent(); testComponent.FileName = "2.txt"; + InitializeDataGridView(); } private void buttonSaveText_Click(object sender, EventArgs e) @@ -27,7 +29,60 @@ namespace ComponentsView private void buttonSaveTextWord_Click(object sender, EventArgs e) { - componentBigText.SetText(string.Empty); + try + { + var docEntry = new DocumentSymple(@"C:\Users\Natalia\Desktop\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) + { + MessageBox.Show(ex.Message, "!", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void InitializeDataGridView() + { + dataGridViewTable.Columns.Add("Column1", ""); + dataGridViewTable.Columns.Add("Column2", ""); + + // + dataGridViewTable.Rows.Add("1", "1"); + dataGridViewTable.Rows.Add("2", "2"); + } + + private void buttonSaveTable_Click(object sender, EventArgs e) + { + try + { + List data = new List(); + + // DataGridView + foreach (DataGridViewRow row in dataGridViewTable.Rows) + { + 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); + } + + // + var docEntry = new DocumentSymple(@"C:\Users\Natalia\Desktop\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, "!", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } } diff --git a/ComponentsView/FormComponents.resx b/ComponentsView/FormComponents.resx index 0791a11..2bef43e 100644 --- a/ComponentsView/FormComponents.resx +++ b/ComponentsView/FormComponents.resx @@ -123,4 +123,7 @@ 154, 17 + + 308, 17 + \ No newline at end of file