diff --git a/UserComponentsOption19/TestAppForCheckComponentsWorking/FormTestNoVisibleComponents.cs b/UserComponentsOption19/TestAppForCheckComponentsWorking/FormTestNoVisibleComponents.cs index d2556c0..50cc694 100644 --- a/UserComponentsOption19/TestAppForCheckComponentsWorking/FormTestNoVisibleComponents.cs +++ b/UserComponentsOption19/TestAppForCheckComponentsWorking/FormTestNoVisibleComponents.cs @@ -39,11 +39,11 @@ namespace TestAppForCheckComponentsWorking string filePath = saveFileDialog.FileName; var dataList = new List{ - new Employee { Id = 1, Status = "нет", FirstName = "Иван", LastName = "Иванов", Age = 34, Children = "нет", Car = "есть", Position = "Инж.", Department = "Деп.", Bonus = 2000.1 }, - new Employee { Id = 2, Status = "есть", FirstName = "Петр", LastName = "Петров", Age = 44, Children = "есть", Car = "есть", Position = "Инж.", Department = "Деп.", Bonus = 2000.1 }, - new Employee { Id = 3, Status = "да", FirstName = "Сергей", LastName = "Сергеев", Age = 55, Children = "да", Car = "есть", Position = "Рук.", Department = "Деп.", Bonus = 5000.5 }, - new Employee { Id = 4, Status = "есть", FirstName = "Ольга", LastName = "Иванова", Age = 34, Children = "есть", Car = "нет", Position = "Бух.", Department = "Бухг.", Bonus = 2000.1 }, - new Employee { Id = 5, Status = "да", FirstName = "Татьяна", LastName = "Петрова", Age = 44, Children = "да", Car = "нет", Position = "Ст. бух.", Department = "Бухг.", Bonus = 7000.6 } + new Employee { Id = 1, Status = "нет", FirstName = "Иван", LastName = "Иванов", Age = 34, Children = "нет", Car = "есть", Position = "Инж.", Departament = "Деп.", Bonus = 2000.1 }, + new Employee { Id = 2, Status = "есть", FirstName = "Петр", LastName = "Петров", Age = 44, Children = "есть", Car = "есть", Position = "Инж.", Departament = "Деп.", Bonus = 2000.1 }, + new Employee { Id = 3, Status = "да", FirstName = "Сергей", LastName = "Сергеев", Age = 55, Children = "да", Car = "есть", Position = "Рук.", Departament = "Деп.", Bonus = 5000.5 }, + new Employee { Id = 4, Status = "есть", FirstName = "Ольга", LastName = "Иванова", Age = 34, Children = "есть", Car = "нет", Position = "Бух.", Departament = "Бухг.", Bonus = 2000.1 }, + new Employee { Id = 5, Status = "да", FirstName = "Татьяна", LastName = "Петрова", Age = 44, Children = "да", Car = "нет", Position = "Ст. бух.", Departament = "Бухг.", Bonus = 7000.6 } }; string[] headerRow1 = { "Идент.", "Статус", "Личные данные", "Личные данные", "Личные данные", "Дети", "Машина", "Работа", "Работа", "Премия" }; @@ -103,7 +103,7 @@ namespace TestAppForCheckComponentsWorking public string Car { get; set; } = string.Empty; - public string Department { get; set; } = string.Empty; + public string Departament { get; set; } = string.Empty; public string Position { get; set; } = string.Empty; diff --git a/UserComponentsOption19/UserComponentsOption19/TableWordNoVisibleComponent.cs b/UserComponentsOption19/UserComponentsOption19/TableWordNoVisibleComponent.cs index f0e1daf..66febc6 100644 --- a/UserComponentsOption19/UserComponentsOption19/TableWordNoVisibleComponent.cs +++ b/UserComponentsOption19/UserComponentsOption19/TableWordNoVisibleComponent.cs @@ -39,21 +39,14 @@ namespace UserComponentsOption19 // Добавление таблицы var tableRange = document.Bookmarks["\\endofdoc"].Range; - Table table = document.Tables.Add(tableRange, 1, headerRow1.Length); + Table table = document.Tables.Add(tableRange, data.Count + 2, headerRow1.Length); + table.Borders.Enable = 1; // Заполнение данных - FillData(table, data, columnPropertyMapping); - - //// Настройка ширины столбцов - //for (int i = 0; i < columnWidths.Count; i++) - //{ - // table.Columns[i].Width = (columnWidths[i]); - //} - + FillData(table, data, columnPropertyMapping, columnWidths); // Заполнение заголовка FillHeader(table, headerRow1, headerRow2, mergeColumns); - // Сохранение документа document.SaveAs2(filePath); document.Close(); @@ -81,62 +74,47 @@ namespace UserComponentsOption19 private void FillHeader(Table table, string[] headerRow1, string[] headerRow2, List<(int start, int end)> mergeColumns) { - // Заполнение второй строки заголовка без объединений for (int i = 0; i < headerRow2.Length; i++) { - table.Cell(2, i).Range.Text = headerRow2[i]; + table.Cell(2, i + 1).Range.Text = headerRow2[i]; } - for (int i = headerRow1.Length - 1; i > 0; i--) + + var sortDeskMergeColumns = mergeColumns.OrderByDescending(x => x.start); + + List notMergedColumns = new List(); + + for (int i = 0; i < table.Columns.Count; i++) { - // Проверяем, нужно ли объединять текущий столбец - foreach (var merge in mergeColumns) + notMergedColumns.Add(i); + } + + for (int i = 0; i < table.Columns.Count; i++) + { + foreach (var item in mergeColumns) { - if (merge.start == i) - { - // Объединяем столбцы от merge.start до merge.end - table.Cell(1, merge.start).Merge(table.Cell(1, merge.end)); - - // Заполняем объединённую ячейку текстом - table.Cell(1, merge.end).Range.Text = headerRow1[i]; - - break; - } - else - { - table.Cell(1, i).Range.Text = headerRow1[i]; - } + if (i >= item.start && i <= item.end) notMergedColumns.Remove(i) +; } } + + foreach (var item in notMergedColumns) + { + table.Cell(1, item + 1).Merge(table.Cell(2, item + 1)); + table.Cell(1, item + 1).Range.Text = headerRow1[item]; + } + + foreach (var item in sortDeskMergeColumns) + { + table.Cell(1, item.start + 1).Merge(table.Cell(1, item.end + 1)); + + table.Cell(1, item.start + 1).Range.Text = headerRow1[item.start]; + } } - private void FillData(Table table, List data, Dictionary columnPropertyMapping) where T : class + private void FillData(Table table, List data, Dictionary columnPropertyMapping, List columnWidths) where T : class { - - //int rowIndex = 3; // Начинаем с третьей строки таблицы - - //foreach (var item in data) // Проходим по каждому объекту в списке данных - //{ - // for (int i = 0; i < columnPropertyMapping.Count; i++) - // { - // if (columnPropertyMapping.TryGetValue(i, out string propName)) // Получаем имя свойства - // { - // var property = typeof(T).GetProperty(propName); // Находим свойство по имени - // if (property != null) - // { - // var valueProp = property.GetValue(item)?.ToString() ?? string.Empty; // Получаем значение свойства - // table.Cell(rowIndex, i).Range.Text = valueProp; // Заполняем ячейку - // } - // else - // { - // table.Cell(rowIndex, i).Range.Text = string.Empty; // Пустая ячейка, если свойство не найдено - // } - // } - // } - // rowIndex++; - //} - int rowIndex = 3; - foreach (var item in data) // Проходим по каждому объекту в списке данных + foreach (var item in data) { for (int i = 0; i < columnPropertyMapping.Count; i++) { @@ -145,276 +123,15 @@ namespace UserComponentsOption19 if (property != null) { var valueProp = property.GetValue(item)?.ToString() ?? string.Empty; - table.Cell(rowIndex, i).Range.Text = valueProp; + table.Cell(rowIndex, i + 1).Range.Text = valueProp; } else { - table.Cell(rowIndex, i).Range.Text = string.Empty; + table.Cell(rowIndex, i + 1).Range.Text = string.Empty; } - rowIndex++; } + rowIndex++; } - - - //{ - // TableRow dataRow = new TableRow(); - - // // Проходим по каждому столбцу и вытаскиваем соответствующее свойство - // for (int columnIndex = 0; columnIndex < columnPropertyMapping.Count; columnIndex++) - // { - // string propertyName = columnPropertyMapping[columnIndex]; - // var property = typeof(T).GetProperty(propertyName); - // if (property != null) - // { - // var value = property.GetValue(data)?.ToString() ?? string.Empty; - // TableCell dataCell = new TableCell(new Paragraph(new Run(new Text(value)))); - // dataRow.Append(dataCell); - // } - // else - // { - // // Если свойство не найдено, добавляем пустую ячейку - // TableCell emptyCell = new TableCell(new Paragraph(new Run(new Text("")))); - // dataRow.Append(emptyCell); - // } - // } - - // return dataRow; - - } - } } - - - -//public void CreateWordDocumentWithTable(string filePath, -// string title, -// List<(int StartColumn, int EndColumn)> columnMerges, -// List columnWidths, -// List headerTitles, -// List dataList, -// Dictionary columnPropertyMapping) where T : class -//{ -// // Проверка на корректность входных данных -// if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(title) || headerTitles == null || headerTitles.Count != 2 || dataList == null || columnWidths == null) -// { -// throw new ArgumentException("Некорректные входные данные."); -// } - -// if (headerTitles[0].Length != headerTitles[1].Length || columnWidths.Count != headerTitles[0].Length) -// { -// throw new ArgumentException("Неверные размеры заголовков или ширин колонок."); -// } - -// using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) -// { -// // Создаем основную часть документа -// MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); -// mainPart.Document = new Document(); -// Body body = new Body(); -// mainPart.Document.AppendChild(body); - -// // Добавляем заголовок документа -// Paragraph titleParagraph = new Paragraph(new Run(new Text(title))); -// body.Append(titleParagraph); - -// // Создаем таблицу -// Table table = new Table(); - -// TableProperties tblProperties = new TableProperties( -// new TableBorders( -// new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -// new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -// new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -// new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -// new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -// new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 } -// ) -// ); - -// table.AppendChild(tblProperties); - -// // Добавляем заголовки таблицы (шапка) -// AddTableHeader(table, headerTitles, columnMerges); - -// // Заполняем таблицу данными из списка объектов T -// foreach (var item in dataList) -// { -// TableRow dataRow = CreateDataRow(item, columnPropertyMapping); -// table.Append(dataRow); -// } - -// // Устанавливаем ширину колонок -// SetColumnWidths(table, columnWidths); - -// // Добавляем таблицу в документ -// body.Append(table); -// mainPart.Document.Save(); -// } -//} - -//private void AddTableHeader(Table table, List headerTitles, List<(int StartColumn, int EndColumn)> columnMerges) -//{ -// TableRow headerRow1 = new(); -// TableRow headerRow2 = new(); - -// for (int i = 0; i < headerTitles[0].Length; i++) -// { -// // Проверяем, нужно ли объединить ячейки в первой строке -// var merge = columnMerges.FirstOrDefault(m => m.StartColumn == i); -// if (merge != default && merge.StartColumn == i) -// { -// // Создаем объединенную ячейку для первой строки -// TableCell mergedCell = new TableCell(new Paragraph(new Run(new Text(headerTitles[0][i])))); -// mergedCell.Append(new TableCellProperties(new HorizontalMerge() { Val = MergedCellValues.Restart })); -// headerRow1.Append(mergedCell); - -// // Добавляем пустые ячейки для остальных объединенных столбцов -// for (int j = i + 1; j <= merge.EndColumn; j++) -// { -// TableCell emptyCell = new TableCell(new Paragraph(new Run(new Text("")))); -// emptyCell.Append(new TableCellProperties(new HorizontalMerge() { Val = MergedCellValues.Continue })); -// headerRow1.Append(emptyCell); -// } - -// i = merge.EndColumn; // Пропускаем объединенные столбцы -// } -// else -// { -// // Если объединение не требуется, добавляем обычную ячейку -// TableCell headerCell1 = new TableCell(new Paragraph(new Run(new Text(headerTitles[0][i])))); -// headerRow1.Append(headerCell1); -// } - -// // Добавляем подзаголовки во вторую строку -// TableCell headerCell2 = new TableCell(new Paragraph(new Run(new Text(headerTitles[1][i])))); -// headerRow2.Append(headerCell2); -// } - -// // Добавляем строки заголовков в таблицу -// table.Append(headerRow1); -// table.Append(headerRow2); -//} - - -//private TableRow CreateDataRow(T data, Dictionary columnPropertyMapping) where T : class -//{ -// TableRow dataRow = new TableRow(); - -// // Проходим по каждому столбцу и вытаскиваем соответствующее свойство -// for (int columnIndex = 0; columnIndex < columnPropertyMapping.Count; columnIndex++) -// { -// string propertyName = columnPropertyMapping[columnIndex]; -// var property = typeof(T).GetProperty(propertyName); -// if (property != null) -// { -// var value = property.GetValue(data)?.ToString() ?? string.Empty; -// TableCell dataCell = new TableCell(new Paragraph(new Run(new Text(value)))); -// dataRow.Append(dataCell); -// } -// else -// { -// // Если свойство не найдено, добавляем пустую ячейку -// TableCell emptyCell = new TableCell(new Paragraph(new Run(new Text("")))); -// dataRow.Append(emptyCell); -// } -// } - -// return dataRow; -//} - - -//private void SetColumnWidths(Table table, List columnWidths) -//{ -// TableGrid tableGrid = new TableGrid(); -// foreach (var width in columnWidths) -// { -// tableGrid.Append(new GridColumn() { Width = (width * 100).ToString() }); // Ширину нужно умножить на 100 для Word -// } -// table.Append(tableGrid); -//} - - -////public void CreateWordTestTable(string filePath) -////{ -//// using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) -//// { -//// // Создаем основную часть документа -//// MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); -//// mainPart.Document = new Document(); -//// Body body = new Body(); -//// mainPart.Document.Append(body); - -//// // Создаем таблицу -//// Table table = new Table(); - -//// TableProperties tblProperties = new TableProperties( -//// new TableBorders( -//// new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -//// new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -//// new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -//// new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -//// new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, -//// new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 } -//// ) -//// ); - -//// table.AppendChild(tblProperties); - -//// // Добавляем строки и объединяем ячейки -//// TableRow row1 = new TableRow(); -//// TableCell cell1 = new TableCell(new Paragraph(new Run(new Text("Объединенная ячейка")))); -//// cell1.Append(new TableCellProperties(new HorizontalMerge() { Val = MergedCellValues.Restart })); -//// row1.Append(cell1); -//// row1.Append(new TableCell(new Paragraph(new Run(new Text("Ячейка 2"))))); -//// row1.Append(new TableCell(new Paragraph(new Run(new Text("Ячейка 3"))))); -//// table.Append(row1); - -//// TableRow row2 = new TableRow(); -//// TableCell cell2 = new TableCell(new Paragraph(new Run(new Text("Объединенная ячейка по строкам")))); -//// cell2.Append(new TableCellProperties(new VerticalMerge() { Val = MergedCellValues.Restart })); -//// row2.Append(cell2); -//// row2.Append(new TableCell(new Paragraph(new Run(new Text("Ячейка 5"))))); -//// row2.Append(new TableCell(new Paragraph(new Run(new Text("Ячейка 6"))))); -//// table.Append(row2); - -//// // Добавляем еще одну строку для завершения вертикального объединения -//// TableRow row3 = new TableRow(); -//// row3.Append(new TableCell(new Paragraph(new Run(new Text(""))))); // Пустая ячейка для вертикального объединения -//// row3.Append(new TableCell(new Paragraph(new Run(new Text("Ячейка 8"))))); -//// row3.Append(new TableCell(new Paragraph(new Run(new Text("Ячейка 9"))))); -//// table.Append(row3); - -//// // Добавляем таблицу в документ -//// body.Append(table); -//// mainPart.Document.Save(); -//// } -////} - - -////private TableRow CreateDataRow(T data, Dictionary columnPropertyMapping) where T : class -////{ -//// TableRow dataRow = new TableRow(); - -//// // Проходим по каждому столбцу и вытаскиваем соответствующее свойство -//// for (int columnIndex = 0; columnIndex < columnPropertyMapping.Count; columnIndex++) -//// { -//// string propertyName = columnPropertyMapping[columnIndex]; -//// var property = typeof(T).GetProperty(propertyName); -//// if (property != null) -//// { -//// var value = property.GetValue(data)?.ToString() ?? string.Empty; -//// TableCell dataCell = new TableCell(new Paragraph(new Run(new Text(value)))); -//// dataRow.Append(dataCell); -//// } -//// else -//// { -//// // Если свойство не найдено, добавляем пустую ячейку -//// TableCell emptyCell = new TableCell(new Paragraph(new Run(new Text("")))); -//// dataRow.Append(emptyCell); -//// } -//// } - -//// return dataRow; -////}