lab 2 in process

This commit is contained in:
revengel66 2024-10-28 20:23:38 +04:00
parent e6dd043cbb
commit 19b9d83d74
14 changed files with 331 additions and 321 deletions

View File

@ -1,4 +1,5 @@
using DocumentFormat.OpenXml; using ComponentsLibrary.entities;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing; using DocumentFormat.OpenXml.Wordprocessing;
using System.ComponentModel; using System.ComponentModel;
@ -6,7 +7,7 @@ using System.ComponentModel;
namespace ComponentsLibrary namespace ComponentsLibrary
{ {
public partial class ComponentBigText : Component public partial class ComponentBigText : Component
{ {
public ComponentBigText() public ComponentBigText()
{ {
@ -16,37 +17,71 @@ namespace ComponentsLibrary
public ComponentBigText(IContainer container) public ComponentBigText(IContainer container)
{ {
container.Add(this); container.Add(this);
InitializeComponent(); InitializeComponent();
} }
//публичный метод public void CreateWordText(DocumentSymple docInfo)
public void SetText(string fileUrl, string fileName, string[] text)
{ {
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(); MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document(); 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))); Paragraph paragraph = new Paragraph(new Run(new Text(line)));
body.Append(paragraph); 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;
} }
} }
} }

View File

@ -1,5 +1,6 @@
using DocumentFormat.OpenXml.Packaging; using Aspose.Words;
using DocumentFormat.OpenXml.Wordprocessing; using Aspose.Words.Tables;
using ComponentsLibrary.entities;
using System.ComponentModel; using System.ComponentModel;
@ -18,94 +19,126 @@ namespace ComponentsLibrary
InitializeComponent(); InitializeComponent();
} }
/* public void CreateTable<T>(DocumentTable<T> tableWord) where T : class
public void CreateDocument(string filePath, DocumentTable<T> documentTable)
{ {
ValidateInput(documentTable); // Проверка наличия данных и определений столбцов
if (tableWord.Items == null || tableWord.Items.Count == 0 || tableWord.ColumnParameters == null || tableWord.ColumnParameters.Count == 0)
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
{ {
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart(); throw new ArgumentException("Не все данные заполнены");
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<T> 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) foreach (var columnParameters in tableWord.ColumnParameters)
{ {
if (string.IsNullOrEmpty(header)) if (string.IsNullOrEmpty(columnParameters.PropertyName))
throw new ArgumentException("Все заголовки должны быть заполнены.");
}
}
private void CreateHeaderRows(DocumentTable<T> 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])))); throw new ArgumentException($"Incomplete column definition: {columnParameters.FirstRowHeader}");
if (!documentTable.MergedColumns.Contains(colIndex)) }
}
// Создание документа
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<int> 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<T> 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);
}
}*/
}
} }

View File

@ -8,6 +8,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Aspose.Words" Version="24.10.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" /> <PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
</ItemGroup> </ItemGroup>

View File

@ -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;
}
}
}

View File

@ -1,31 +0,0 @@

namespace ComponentsLibrary
{
public class DocumentTable<T>
{
public string DocumentTitle { get; set; } = string.Empty;
public string DocumentPath { get; set; } = string.Empty;
public List<int> MergedColumns { get; set; }
public List<double> ColumnWidths { get; set; }
public List<string> Headers { get; set; }
public List<T> Data { get; set; }
public List<string> PropertyMappings { get; set; }
public DocumentTable(string documentTitle,
string documentPath,
List<int> mergedColumns,
List<double> columnWidths,
List<string> headers,
List<T> data,
List<string> propertyMappings)
{
DocumentTitle = documentTitle;
DocumentPath = documentPath;
MergedColumns = mergedColumns;
ColumnWidths = columnWidths;
Headers = headers;
Data = data;
PropertyMappings = propertyMappings;
}
}
}

View File

@ -1,5 +1,4 @@
using ComponentsView; using System.ComponentModel;
using System.ComponentModel;
using static System.Net.Mime.MediaTypeNames; using static System.Net.Mime.MediaTypeNames;
namespace ComponentsLibrary namespace ComponentsLibrary

View File

@ -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; }
}
}

View File

@ -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;
}
}
}

View File

@ -0,0 +1,27 @@
namespace ComponentsLibrary.entities
{
public class DocumentTable<T>
{
//путь до файла
public string FileUrl { get; set; } = string.Empty;
//заголовок в документе
public string Title { get; set; } = string.Empty;
//параметры колонок (ширина и тд)
public List<ColumnParams> ColumnParameters { get; set; } = new();
//данные для таблицы
public List<T> Items { get; set; } = new();
//информация по объединению колонок
public List<int[]> MergedColumns { get; set; } = new();
public DocumentTable(string fileUrl, string title, List<ColumnParams> columnParameters, List<T> data, List<int[]> mergedColumns)
{
FileUrl = fileUrl;
Title = title;
ColumnParameters = columnParameters;
Items = data;
MergedColumns = mergedColumns;
}
}
}

View File

@ -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;
}
}
}

View File

@ -36,9 +36,7 @@
richTextBoxWord = new RichTextBox(); richTextBoxWord = new RichTextBox();
buttonSaveTextWord = new Button(); buttonSaveTextWord = new Button();
componentTable = new ComponentsLibrary.ComponentTable(components); componentTable = new ComponentsLibrary.ComponentTable(components);
dataGridViewTable = new DataGridView();
buttonSaveTable = new Button(); buttonSaveTable = new Button();
((System.ComponentModel.ISupportInitialize)dataGridViewTable).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// richTextBoxTest // richTextBoxTest
@ -77,22 +75,13 @@
buttonSaveTextWord.UseVisualStyleBackColor = true; buttonSaveTextWord.UseVisualStyleBackColor = true;
buttonSaveTextWord.Click += buttonSaveTextWord_Click; 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
// //
buttonSaveTable.Location = new Point(12, 316); buttonSaveTable.Location = new Point(12, 143);
buttonSaveTable.Name = "buttonSaveTable"; buttonSaveTable.Name = "buttonSaveTable";
buttonSaveTable.Size = new Size(350, 23); buttonSaveTable.Size = new Size(350, 41);
buttonSaveTable.TabIndex = 5; buttonSaveTable.TabIndex = 5;
buttonSaveTable.Text = "Сохранить"; buttonSaveTable.Text = "Cоздать документ с таблицей";
buttonSaveTable.UseVisualStyleBackColor = true; buttonSaveTable.UseVisualStyleBackColor = true;
buttonSaveTable.Click += buttonSaveTable_Click; buttonSaveTable.Click += buttonSaveTable_Click;
// //
@ -102,14 +91,12 @@
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450); ClientSize = new Size(800, 450);
Controls.Add(buttonSaveTable); Controls.Add(buttonSaveTable);
Controls.Add(dataGridViewTable);
Controls.Add(buttonSaveTextWord); Controls.Add(buttonSaveTextWord);
Controls.Add(richTextBoxWord); Controls.Add(richTextBoxWord);
Controls.Add(buttonSaveText); Controls.Add(buttonSaveText);
Controls.Add(richTextBoxTest); Controls.Add(richTextBoxTest);
Name = "FormComponents"; Name = "FormComponents";
Text = "Form1"; Text = "Form1";
((System.ComponentModel.ISupportInitialize)dataGridViewTable).EndInit();
ResumeLayout(false); ResumeLayout(false);
} }
@ -122,7 +109,6 @@
private RichTextBox richTextBoxWord; private RichTextBox richTextBoxWord;
private Button buttonSaveTextWord; private Button buttonSaveTextWord;
private ComponentsLibrary.ComponentTable componentTable; private ComponentsLibrary.ComponentTable componentTable;
private DataGridView dataGridViewTable;
private Button buttonSaveTable; private Button buttonSaveTable;
} }
} }

View File

@ -1,4 +1,5 @@
using System.Windows.Forms; using System.Windows.Forms;
using ComponentsLibrary.entities;
namespace ComponentsView namespace ComponentsView
{ {
@ -8,7 +9,6 @@ namespace ComponentsView
{ {
InitializeComponent(); InitializeComponent();
testComponent.FileName = "2.txt"; testComponent.FileName = "2.txt";
InitializeDataGridView();
} }
private void buttonSaveText_Click(object sender, EventArgs e) private void buttonSaveText_Click(object sender, EventArgs e)
@ -29,62 +29,84 @@ namespace ComponentsView
private void buttonSaveTextWord_Click(object sender, EventArgs e) 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); Filter = "docx|*.docx"
componentBigText.SetText(docEntry.FileUrl, docEntry.FileName, docEntry.Text); };
MessageBox.Show("Ñîõàðíåíî óñïåøíî", "Ðåçóëüòàò", if (dialog.ShowDialog() == DialogResult.OK)
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{ {
MessageBox.Show(ex.Message, "Îøèáêà!", try
MessageBoxButtons.OK, MessageBoxIcon.Error); {
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) private void buttonSaveTable_Click(object sender, EventArgs e)
{ {
try List<int[]> mergedColumns = new()
{ {
List<string[]> data = new List<string[]>(); new int[] { 1, 5 },
new int[] { 6, 7 },
};
// Èçâëå÷åíèå äàííûõ èç DataGridView var columns = new List<ColumnParams>
foreach (DataGridViewRow row in dataGridViewTable.Rows) {
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<Employee>
{
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; // Ïðîïóñòèòü ïóñòóþ ñòðîêó DocumentTable<Employee> info = new(dialog.FileName, "Çàäàíèå 2", columns, employees, mergedColumns);
string[] rowData = new string[dataGridViewTable.Columns.Count]; componentTable.CreateTable(info);
for (int i = 0; i < dataGridViewTable.Columns.Count; i++)
{ MessageBox.Show("Ñîõðàíåíî óñïåøíî", "Ðåçóëüòàò",
rowData[i] = row.Cells[i].Value?.ToString() ?? string.Empty; MessageBoxButtons.OK, MessageBoxIcon.Information);
}
data.Add(rowData);
} }
catch (Exception ex)
// Ñîçäàíèå äîêóìåíòà ñ äàííûìè èç òàáëèöû {
var docEntry = new DocumentSymple(@"\5semestr\KOP\KOP-PIbd-32-Katysheva-N-E\docs", "Table.docx", data.Select(row => string.Join("\t", row)).ToArray()); MessageBox.Show(ex.Message, "Îøèáêà!",
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); MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
} }
} }

View File

@ -126,4 +126,7 @@
<metadata name="componentTable.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="componentTable.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>308, 17</value> <value>308, 17</value>
</metadata> </metadata>
<metadata name="componentTable2.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>451, 17</value>
</metadata>
</root> </root>

View File

@ -13,120 +13,8 @@ namespace ComponentsView
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
//ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
//Application.Run(new FormComponents()); 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>(BorderValues.Single),
Size = 12
},
new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
}
)
);
table.AppendChild<TableProperties>(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<RunProperties>(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();
}
}
} }
} }
} }