PIbd-32_Rogashova_E.A._COP_1/COPWinForms/ComponentWord2.cs

177 lines
6.3 KiB
C#

using Aspose.Words.Drawing.Charts;
using Aspose.Words;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Words.Tables;
using static COPWinForms.ComponentWord2;
namespace COPWinForms
{
public partial class ComponentWord2 : Component
{
private string _fileName;
public string FileName
{
set
{
if (string.IsNullOrEmpty(value))
{
return;
}
if (!value.EndsWith(".docx"))
{
throw new ArgumentException("No docx file");
}
_fileName = value;
}
}
public ComponentWord2()
{
InitializeComponent();
}
public ComponentWord2(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateTable<T>(TableWord<T> tableWord) where T : class
{
// Проверка наличия данных и определений столбцов
if (tableWord.Data == null)
{
throw new ArgumentException("Data or column definitions are null or empty");
}
// Проверка, что все ячейки шапки заполнены и для каждого столбца определено свойство/поле класса
foreach (var columnDefinition in tableWord.ColumnDefinitions)
{
if (string.IsNullOrEmpty(columnDefinition.PropertyName))
{
throw new ArgumentException($"Incomplete column definition: {columnDefinition.Header}");
}
}
// Создание документа
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.DocumentTitle);
// Создание таблицы
Table table = builder.StartTable();
int ColInd1 = 0;
foreach (var columnDefinition in tableWord.ColumnDefinitions)
{
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnDefinition.Width);
builder.Write(columnDefinition.Header);
ColInd1++;
}
// Объединение ячеек в первой строке шапки таблицы
foreach (var mergedColumn in tableWord.MergedColumns)
{
int startCellIndex = mergedColumn[0];
int endCellIndex = mergedColumn[mergedColumn.Length - 1];
// Объединение ячеек в первой строке шапки таблицы
for (int i = startCellIndex; i <= endCellIndex; i++)
{
table.Rows[0].Cells[i].CellFormat.HorizontalMerge = CellMerge.First;
}
// Если столбцов для объединения больше одного, то нужно объединять остальные ячейки в первой строке
if (endCellIndex - startCellIndex > 0)
{
for (int i = startCellIndex + 1; i <= endCellIndex; i++)
{
table.Rows[0].Cells[i].CellFormat.HorizontalMerge = CellMerge.Previous;
}
}
}
builder.EndRow();
int ColInd = 0;
foreach (var columnDefinition2 in tableWord.ColumnDefinitions2)
{
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnDefinition2.Width);
builder.Write(columnDefinition2.Header);
ColInd++;
}
builder.EndRow();
int columnIndex;
foreach (var columnDefinition in tableWord.ColumnDefinitions)
{
string currentPropertyName = columnDefinition.PropertyName;
columnIndex = 0;
foreach (var columnDefinition2 in tableWord.ColumnDefinitions2)
{
string currentPropertyName1 = columnDefinition2.PropertyName;
if (currentPropertyName == currentPropertyName1)
{
table.Rows[0].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.First;
table.Rows[1].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.Previous;
}
columnIndex++;
}
}
// Вставка данных в таблицу
foreach (var item in tableWord.Data)
{
foreach (var columnDefinition2 in tableWord.ColumnDefinitions2)
{
builder.InsertCell();
// Получение значения свойства/поля объекта по заданному имени
var propertyValue = item.GetType()
.GetProperty(columnDefinition2.PropertyName)?
.GetValue(item)?.ToString();
// Вставка значения в ячейку
builder.Write(propertyValue ?? "");
}
builder.EndRow();
}builder.EndTable();
// Сохранение документа в файл
document.Save(tableWord.FilePath);
}
public class ColumnDefinition
{
public string Header { get; set; }
public string PropertyName { get; set; }
public int Width { get; set; }
}
}
}