Lab2 готово

This commit is contained in:
Yunusov_Niyaz 2024-10-11 04:47:06 +04:00
parent 193a9f1ab8
commit b3c5ccb7bc
30 changed files with 1070 additions and 39 deletions

View File

@ -11,7 +11,7 @@
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
public void Dispose(bool disposing)
{
if (disposing && (components != null))
{
@ -28,6 +28,7 @@
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
selectComponent = new YunusovComponentsLibrary.SelectedComponent();
groupBoxSelect = new GroupBox();
buttonGetSelected = new Button();
@ -42,9 +43,21 @@
buttonAddListOutput = new Button();
buttonClearListOutput = new Button();
listOutputComponent = new YunusovComponentsLibrary.ListOutputComponent();
wordDocumentContext1 = new YunusovComponentsLibrary.WordDocumentContext(components);
groupBoxSimpelTable = new GroupBox();
buttonSimpleTable = new Button();
groupBoxDiagram = new GroupBox();
buttonCreateDiagram = new Button();
wordDiagram = new YunusovComponentsLibrary.WordDiagram(components);
groupBoxTableWithHeaders = new GroupBox();
buttonWordTableWithHeaders = new Button();
wordDocumentTable1 = new YunusovComponentsLibrary.WordDocumentTable(components);
groupBoxSelect.SuspendLayout();
groupBoxInput.SuspendLayout();
groupBoxListOutput.SuspendLayout();
groupBoxSimpelTable.SuspendLayout();
groupBoxDiagram.SuspendLayout();
groupBoxTableWithHeaders.SuspendLayout();
SuspendLayout();
//
// selectComponent
@ -182,14 +195,77 @@
listOutputComponent.Location = new Point(6, 26);
listOutputComponent.Name = "listOutputComponent";
listOutputComponent.SelectedRow = -1;
listOutputComponent.Size = new Size(414, 204);
listOutputComponent.Size = new Size(445, 209);
listOutputComponent.TabIndex = 0;
//
// groupBoxSimpelTable
//
groupBoxSimpelTable.Controls.Add(buttonSimpleTable);
groupBoxSimpelTable.Location = new Point(12, 265);
groupBoxSimpelTable.Name = "groupBoxSimpelTable";
groupBoxSimpelTable.Size = new Size(152, 101);
groupBoxSimpelTable.TabIndex = 5;
groupBoxSimpelTable.TabStop = false;
groupBoxSimpelTable.Text = "SimpleTable";
//
// buttonSimpleTable
//
buttonSimpleTable.Location = new Point(6, 40);
buttonSimpleTable.Name = "buttonSimpleTable";
buttonSimpleTable.Size = new Size(138, 29);
buttonSimpleTable.TabIndex = 6;
buttonSimpleTable.Text = "Word таблицы";
buttonSimpleTable.UseVisualStyleBackColor = true;
buttonSimpleTable.Click += buttonSimpleTable_Click;
//
// groupBoxDiagram
//
groupBoxDiagram.Controls.Add(buttonCreateDiagram);
groupBoxDiagram.Location = new Point(366, 265);
groupBoxDiagram.Name = "groupBoxDiagram";
groupBoxDiagram.Size = new Size(181, 101);
groupBoxDiagram.TabIndex = 6;
groupBoxDiagram.TabStop = false;
groupBoxDiagram.Text = "Histogramma";
//
// buttonCreateDiagram
//
buttonCreateDiagram.Location = new Point(23, 40);
buttonCreateDiagram.Name = "buttonCreateDiagram";
buttonCreateDiagram.Size = new Size(127, 29);
buttonCreateDiagram.TabIndex = 0;
buttonCreateDiagram.Text = "Создать Word";
buttonCreateDiagram.UseVisualStyleBackColor = true;
buttonCreateDiagram.Click += createDiagram_Click;
//
// groupBoxTableWithHeaders
//
groupBoxTableWithHeaders.Controls.Add(buttonWordTableWithHeaders);
groupBoxTableWithHeaders.Location = new Point(183, 265);
groupBoxTableWithHeaders.Name = "groupBoxTableWithHeaders";
groupBoxTableWithHeaders.Size = new Size(159, 101);
groupBoxTableWithHeaders.TabIndex = 7;
groupBoxTableWithHeaders.TabStop = false;
groupBoxTableWithHeaders.Text = "TableWithHeaders";
//
// buttonWordTableWithHeaders
//
buttonWordTableWithHeaders.Location = new Point(6, 40);
buttonWordTableWithHeaders.Name = "buttonWordTableWithHeaders";
buttonWordTableWithHeaders.Size = new Size(132, 29);
buttonWordTableWithHeaders.TabIndex = 0;
buttonWordTableWithHeaders.Text = "Word таблица";
buttonWordTableWithHeaders.UseVisualStyleBackColor = true;
buttonWordTableWithHeaders.Click += WordSaveHeaders_Click;
//
// Form1
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1174, 641);
ClientSize = new Size(1174, 376);
Controls.Add(groupBoxTableWithHeaders);
Controls.Add(groupBoxDiagram);
Controls.Add(groupBoxSimpelTable);
Controls.Add(groupBoxListOutput);
Controls.Add(groupBoxInput);
Controls.Add(groupBoxSelect);
@ -199,6 +275,9 @@
groupBoxSelect.PerformLayout();
groupBoxInput.ResumeLayout(false);
groupBoxListOutput.ResumeLayout(false);
groupBoxSimpelTable.ResumeLayout(false);
groupBoxDiagram.ResumeLayout(false);
groupBoxTableWithHeaders.ResumeLayout(false);
ResumeLayout(false);
}
@ -218,5 +297,14 @@
private Button buttonGetListOutput;
private Button buttonAddListOutput;
private Button buttonClearListOutput;
private YunusovComponentsLibrary.WordDocumentContext wordDocumentContext1;
private GroupBox groupBoxSimpelTable;
private Button buttonSimpleTable;
private GroupBox groupBoxDiagram;
private Button buttonCreateDiagram;
private YunusovComponentsLibrary.WordDiagram wordDiagram;
private GroupBox groupBoxTableWithHeaders;
private Button buttonWordTableWithHeaders;
private YunusovComponentsLibrary.WordDocumentTable wordDocumentTable1;
}
}

View File

@ -1,6 +1,10 @@
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.VisualBasic.Devices;
using System.Windows.Forms;
using YunusovComponentsLibrary;
using YunusovComponentsLibrary.Exceptions;
using YunusovComponentsLibrary.OfficePackage.HelperModels;
namespace Form1
{
@ -67,11 +71,10 @@ namespace Form1
{
listOutputComponent.ConfigColumn(new()
{
ColumnsCount = 4,
Header = new string[] { "ID", "Èìÿ", "Ôàìèëèÿ", "Âîçðàñò" },
Width = new int[] { 10, 150, 150, 100 },
IsVisible = new bool[] { false, true, true, true },
PropertiesName = new string[] { "Id", "Name", "Yourname", "Age" }
new ColumnInfo("", 0, false, "Id"),
new ColumnInfo("Ôàìèëèÿ", 150, true, "Name"),
new ColumnInfo("Èìÿ", 100, true, "Surname"),
new ColumnInfo("Âîçðàñò", 100, true, "Age"),
});
List<TestPerson> Persons = new()
{
@ -103,5 +106,100 @@ namespace Form1
var Test = listOutputComponent.GetSelectedObject<TestPerson>();
MessageBox.Show(Test.ToString());
}
#region ïðîñòàÿ òàáëèöàÿ
private void buttonSimpleTable_Click(object sender, EventArgs e)
{
List<string[,]> data = new List<string[,]>
{
new string[,]
{
{ "Ñòð 1 Êîë 1", "Ñòð 1 Êîë 2", "Ñòð 1 Êîë 3" },
{ "Ñòð 2 Êîë 1", "Ñòð 2 Êîë 2", "Ñòð 2 Êîë 3" }
},
new string[,]
{
{ "Ñòð 1 Êîë 1", "Ñòð 1 Êîë 2", "Ñòð 1 Êîë 3", "Ñòð 1 Êîë 4", "Ñòð 1 Êîë 5", "Ñòð 1 Êîë 6" },
{ "Ñòð 2 Êîë 1", "Ñòð 2 Êîë 2", "Ñòð 2 Êîë 3", "Ñòð 2 Êîë 4", "Ñòð 2 Êîë 5", "Ñòð 2 Êîë 6" },
{ "Ñòð 3 Êîë 1", "Ñòð 3 Êîë 2", "Ñòð 3 Êîë 3", "Ñòð 3 Êîë 4", "Ñòð 3 Êîë 5", "Ñòð 3 Êîë 6" },
{ "Ñòð 4 Êîë 1", "Ñòð 4 Êîë 2", "Ñòð 4 Êîë 3", "Ñòð 4 Êîë 4", "Ñòð 4 Êîë 5", "Ñòð 4 Êîë 6" },
}
};
var info = new WordSimpleTable
{
FileName = "C://Users//niyaz//WordSimpleTable.docx",
Title = "Çàãîëîâîê",
Table = data,
};
wordDocumentContext1.CreateWord(info);
MessageBox.Show("Word óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
#region ñëîæíàÿ òàáëèöà
readonly List<PersonWordTable> PersonsWord = new()
{
new PersonWordTable("Äåïàðòàìåíò", "Âÿ÷åñëàâ", "Èâàíîâ", 20, 2000.1),
new PersonWordTable("Äåïàðòàìåíò", "Ðîñòèñëàâ", "Çàõàðîâ", 20, 3000.5),
new PersonWordTable("Äåïàðòàìåíò", "Ñåðãåé", "Ñåðãååâ", 59, 1001.3),
new PersonWordTable("Áóõãàëòåðèÿ", "Àðò¸ì", "ßøèí", 25, 1234.23),
new PersonWordTable("Áóõãàëòåðèÿ", "Ëåâ", "ßøèí", 89, 1457.34),
};
private void WordSaveHeaders_Click(object sender, EventArgs e)
{
wordDocumentTable1.CreateTable(new WordTableWithData<PersonWordTable>
{
FileName = "C://Users//niyaz//OneDrive//Äîêóìåíòû//HeaderTable.docx",
Title = "Çàãîëîâîê",
ColumnsRowsWidth = new List<(int Column, int Row)> { (5, 5), (10, 5), (10, 0), (5, 0), (10,5) },
Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>
{
(0, 0, "Division", "Id"),
(1, 0, "Surname", "Surname"),
(2, 0, "Name", "Name"),
(3, 0, "Age", "Age"),
(4, 0, "Premia", "Premia"),
},
Data = PersonsWord,
NullReplace = "null"
});
MessageBox.Show("Word äîêóìåíò ñ òàáëèöåé ñîçäàí!", "Óñïåõ");
}
#endregion
#region ðàáîòà ñ äèàãðàììîé
private void createDiagram_Click(object sender, EventArgs e)
{
try
{
wordDiagram.CreateDiagram(
new WordDiagramInfo
{
FileName = "C://Users//niyaz//OneDrive//Äîêóìåíòû//Diagram.docx",
Title = "Çàãîëîâîê",
ChartTitle = "Ãèñòîãðàììà",
LegendLocation = YunusovComponentsLibrary.OfficePackage.HelperEnum.WordDiagramLegendLocation.Top,
Series = new WordDiagramSeries
{
SeriesName = "Ãèñòîãðàììà",
Data = new Dictionary<string, double>
{
{ "Windows", 71 },
{ "OS X", 15.5 },
{ "Linux", 4.5 },
{ "Others", 8.5 },
}
}
});
MessageBox.Show("Word äîêóìåíò ñ äèàãðàììîé ñîçäàí!", "Óñïåõ");
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà: {ex.Message}");
}
}
#endregion
}
}

View File

@ -8,6 +8,13 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspose.Words" Version="24.10.0" />
<PackageReference Include="Microsoft.Office.Interop.Excel" Version="15.0.4795.1001" />
<PackageReference Include="Microsoft.Office.Interop.Word" Version="15.0.4797.1004" />
<PackageReference Include="OxyPlot.WindowsForms" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\YunusovComponentsLibrary\YunusovComponentsLibrary.csproj" />
</ItemGroup>

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="wordDocumentContext1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>165, 17</value>
</metadata>
<metadata name="wordDiagram.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="wordDocumentTable1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>383, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,25 @@
namespace YunusovComponentsLibrary
{
public class PersonWordTable
{
public string Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty;
public int Age { get; set; }
public double Premia { get; set; }
public PersonWordTable()
{ }
public PersonWordTable(string Id, string Name, string Surname, int Age, double Premia)
{
this.Id = Id;
this.Name = Name;
this.Surname = Surname;
this.Age = Age;
this.Premia = Premia;
}
}
}

View File

@ -6,22 +6,22 @@
public string Name { get; set; } = string.Empty;
public string Yourname { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty;
public int Age { get; set; }
public TestPerson()
{ }
public TestPerson(int Id, string Name, string Yourname, int Age)
public TestPerson(int Id, string Name, string Surname, int Age)
{
this.Id = Id;
this.Name = Name;
this.Yourname = Yourname;
this.Surname = Surname;
this.Age = Age;
}
public override string ToString()
public string ToString()
{
return $"[{Id}] {Name} {Yourname}. Возраст: {Age}";
return $"{Id}. {Name} {Surname} Возраст: {Age}";
}
}
}

View File

@ -4,13 +4,20 @@
{
public int ColumnsCount { get; set; }
public string[] Header { get; set; }
public string Header { get; set; }
public int[] Width { get; set; }
public int Width { get; set; }
public bool[] IsVisible { get; set; }
public bool IsVisible { get; set; }
public string[] PropertiesName { get; set; }
public string PropertiesName { get; set; }
public ColumnInfo(string Header, int Width, bool IsVisible, string PropertiesName)
{
this.Header = Header;
this.Width = Width;
this.IsVisible = IsVisible;
this.PropertiesName = PropertiesName;
}
}
}

View File

@ -11,7 +11,7 @@
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
public void Dispose(bool disposing)
{
if (disposing && (components != null))
{

View File

@ -11,7 +11,7 @@
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
public void Dispose(bool disposing)
{
if (disposing && (components != null))
{
@ -35,11 +35,12 @@
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(597, 335);
dataGridView.Size = new Size(600, 338);
dataGridView.TabIndex = 0;
//
// ListOutputComponent

View File

@ -34,24 +34,18 @@ namespace YunusovComponentsLibrary
}
}
}
public void ConfigColumn(ColumnInfo columns)
public void ConfigColumn(List<ColumnInfo> columns)
{
if (columns.ColumnsCount != columns.Header.Length ||
columns.ColumnsCount != columns.Width.Length ||
columns.ColumnsCount != columns.IsVisible.Length ||
columns.ColumnsCount != columns.PropertiesName.Length)
throw new ArgumentException("All arrays must have the same length.");
dataGridView.Columns.Clear();
dataGridView.ColumnCount = columns.ColumnsCount;
dataGridView.ColumnCount = columns.Count;
for (int i = 0; i < columns.ColumnsCount; ++i)
for (int i = 0; i < columns.Count; ++i)
{
dataGridView.Columns[i].HeaderText = columns.Header[i];
dataGridView.Columns[i].Width = columns.Width[i];
dataGridView.Columns[i].Visible = columns.IsVisible[i];
dataGridView.Columns[i].Name = columns.PropertiesName[i];
dataGridView.Columns[i].HeaderText = columns[i].Header;
dataGridView.Columns[i].Width = columns[i].Width;
dataGridView.Columns[i].Visible = columns[i].IsVisible;
dataGridView.Columns[i].Name = columns[i].PropertiesName;
}
}
public void ClearDataGridView()
@ -60,7 +54,7 @@ namespace YunusovComponentsLibrary
}
public T GetSelectedObject<T>() where T : class, new()
{
T obj = new ();
T obj = new();
var properties = typeof(T).GetProperties();
foreach (var property in properties)
@ -81,10 +75,11 @@ namespace YunusovComponentsLibrary
int rowIndex = dataGridView.Rows.Add();
foreach (var property in typeof(T).GetProperties())
foreach (DataGridViewColumn Column in dataGridView.Columns)
{
var value = property.GetValue(item);
dataGridView.Rows[rowIndex].Cells[property.Name].Value = value;
var Property = typeof(T).GetProperties().FirstOrDefault(x => x.Name == Column.Name);
var Value = Property.GetValue(item);
dataGridView.Rows[rowIndex].Cells[Column.Index].Value = Value;
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YunusovComponentsLibrary.OfficePackage.HelperEnum
{
public enum WordDiagramLegendLocation
{
Left,
Right,
Top,
Bottom,
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YunusovComponentsLibrary.OfficePackage.HelperEnum
{
public enum WordJustificationType
{
Center,
Both
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunusovComponentsLibrary.OfficePackage.HelperEnum;
namespace YunusovComponentsLibrary.OfficePackage.HelperModels
{
public class WordDiagramInfo : WordInfo
{
public string ChartTitle { get; set; } = string.Empty;
public WordDiagramLegendLocation LegendLocation { get; set; } = WordDiagramLegendLocation.Right;
public WordDiagramSeries Series { get; set; } = new();
public void CheckFields()
{
if (string.IsNullOrEmpty(FileName))
throw new ArgumentNullException(nameof(FileName), "File path and name cannot be null or empty.");
if (string.IsNullOrEmpty(Title))
throw new ArgumentNullException(nameof(Title), "Title cannot be null or empty.");
if (Series == null)
throw new ArgumentNullException(nameof(Series), "Data cannot be null or empty.");
}
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YunusovComponentsLibrary.OfficePackage.HelperModels
{
public class WordDiagramSeries
{
public string SeriesName { get; set; } = string.Empty;
public Dictionary<string, double> Data = new();
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YunusovComponentsLibrary.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,13 @@
using YunusovComponentsLibrary.OfficePackage.HelperEnum;
namespace YunusovComponentsLibrary.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; } = new();
public WordTextProperties? TextProperties { get; set; }
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,15 @@
namespace YunusovComponentsLibrary.OfficePackage.HelperModels
{
public class WordSimpleTable : WordInfo
{
public List<string[,]> Table { get; set; } = new List<string[,]>();
public void CheckFields()
{
if (string.IsNullOrWhiteSpace(FileName) || string.IsNullOrWhiteSpace(Title) || Table == null || Table.Count == 0)
{
throw new ArgumentException("Все поля должны быть заполнены.");
}
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YunusovComponentsLibrary.OfficePackage.HelperModels
{
public class WordTableWithData<T> : WordTableWithHeader
{
public List<T> Data { get; set; }
public void CheckFields()
{
if (Data == null || Data.Count == 0)
throw new ArgumentNullException("No data");
if (ColumnsRowsWidth is null || ColumnsRowsWidth.Count == 0)
throw new ArgumentNullException("Rows width invalid");
if (Headers is null || Headers.Count == 0)
throw new ArgumentNullException("Header data invalid");
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YunusovComponentsLibrary.OfficePackage.HelperModels
{
public class WordTableWithHeader : WordInfo
{
public (int Columns, int Rows) ColumnsRowsDataCount { get; set; }
public List<(int Column, int Row)>? ColumnsRowsWidth { get; init; }
public List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>? Headers { get; init; }
public string NullReplace { get; set; } = "null";
}
}

View File

@ -0,0 +1,11 @@
using YunusovComponentsLibrary.OfficePackage.HelperEnum;
namespace YunusovComponentsLibrary.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; } = string.Empty;
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,231 @@
using YunusovComponentsLibrary.OfficePackage.HelperEnum;
using YunusovComponentsLibrary.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Aspose.Words.Drawing.Charts;
using Aspose.Words;
using Aspose.Words.Drawing;
using Body = DocumentFormat.OpenXml.Wordprocessing.Body;
using Paragraph = DocumentFormat.OpenXml.Wordprocessing.Paragraph;
using Run = DocumentFormat.OpenXml.Wordprocessing.Run;
using Document = DocumentFormat.OpenXml.Wordprocessing.Document;
namespace YunusovComponentsLibrary.OfficePackage.Implements
{
public class SaveToWord
{
private Document _document;
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
/// <summary>
/// Получение типа выравнивания
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center, _ => JustificationValues.Left,
};
}
/// <summary>
/// Настройки страницы
/// </summary>
/// <returns></returns>
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new DocumentFormat.OpenXml.Wordprocessing.PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
/// <summary>
/// Задание форматирования для абзаца
/// </summary>
/// <param name="paragraphProperties"></param>
/// <returns></returns>
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize
{
Val = paragraphProperties.Size
});
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
public void CreateWord(WordInfo info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
public void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
public void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
public void CreateTable(string[,] table)
{
if (_docBody == null || table == null)
{
return;
}
Table docTable = new Table();
TableProperties tableProps = 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
}
));
docTable.AppendChild(tableProps);
TableGrid tableGrid = new TableGrid();
int height = table.GetLength(0);
int width = table.GetLength(1);
for (int i = 0; i < width; i++)
{
tableGrid.AppendChild(new GridColumn());
}
TableRow tableRow = new TableRow();
for (int i = 0; i < height; i++)
{
tableRow = new TableRow();
for (int j = 0; j < width; j++)
{
var element = table[i,j];
tableRow.AppendChild(CreateTableCell(element));
}
docTable.AppendChild(tableRow);
}
_docBody.AppendChild(docTable);
}
private TableCell CreateTableCell(string element)
{
var tableParagraph = new Paragraph();
var run = new Run();
run.AppendChild(new Text { Text = element });
tableParagraph.AppendChild(run);
var tableCell = new TableCell();
tableCell.AppendChild(tableParagraph);
return tableCell;
}
public void CreateDiagram(WordDiagramInfo parameters)
{
Aspose.Words.Document doc = new Aspose.Words.Document();
DocumentBuilder builder = new DocumentBuilder(doc);
if (doc == null)
throw new ArgumentNullException(nameof(doc), "Document is not created.");
builder.ParagraphFormat.Style.Font.Size = 16;
builder.Writeln(parameters.Title);
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
GetLegendPosition(parameters, chart);
ChartSeriesCollection seriesColl = chart.Series;
seriesColl.Clear();
ChartSeries series = chart.Series.Add(parameters.Series.SeriesName, parameters.Series.Data.Select(x => x.Key).ToArray(), parameters.Series.Data.Select(x => x.Value).ToArray());
doc.Save(parameters.FileName);
}
private void GetLegendPosition(WordDiagramInfo parameters, Chart chart)
{
switch (parameters.LegendLocation)
{
case WordDiagramLegendLocation.Left:
chart.Legend.Position = LegendPosition.Left;
break;
case WordDiagramLegendLocation.Right:
chart.Legend.Position = LegendPosition.Right;
break;
case WordDiagramLegendLocation.Top:
chart.Legend.Position = LegendPosition.Top;
break;
case WordDiagramLegendLocation.Bottom:
chart.Legend.Position = LegendPosition.Bottom;
break;
}
}
}
}

View File

@ -11,7 +11,7 @@
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
public void Dispose(bool disposing)
{
if (disposing && (components != null))
{

View File

@ -11,7 +11,7 @@
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
public void Dispose(bool disposing)
{
if (disposing && (components != null))
{

View File

@ -0,0 +1,36 @@
namespace YunusovComponentsLibrary
{
partial class WordDiagram
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunusovComponentsLibrary.OfficePackage.HelperEnum;
using YunusovComponentsLibrary.OfficePackage.HelperModels;
using YunusovComponentsLibrary.OfficePackage.Implements;
namespace YunusovComponentsLibrary
{
public partial class WordDiagram : Component
{
SaveToWord SaveToWord = new SaveToWord();
public WordDiagram()
{
InitializeComponent();
}
public WordDiagram(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDiagram(WordDiagramInfo info)
{
info.CheckFields();
SaveToWord.CreateDiagram(info);
}
}
}

View File

@ -0,0 +1,36 @@
namespace YunusovComponentsLibrary
{
partial class WordDocumentContext
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
public void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,53 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunusovComponentsLibrary.OfficePackage.Implements;
using DocumentFormat.OpenXml.Wordprocessing;
using YunusovComponentsLibrary.OfficePackage.HelperModels;
using YunusovComponentsLibrary.OfficePackage.HelperEnum;
namespace YunusovComponentsLibrary
{
public partial class WordDocumentContext : Component
{
SaveToWord SaveToWord = new SaveToWord();
public WordDocumentContext()
{
InitializeComponent();
}
public WordDocumentContext(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateWord(WordSimpleTable info)
{
info.CheckFields();
SaveToWord.CreateWord(info);
SaveToWord.CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var table in info.Table)
{
SaveToWord.CreateTable(table);
SaveToWord.CreateParagraph(new WordParagraph());
}
SaveToWord.SaveWord(info);
}
}
}

View File

@ -0,0 +1,36 @@
namespace YunusovComponentsLibrary
{
partial class WordDocumentTable
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,200 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using YunusovComponentsLibrary.OfficePackage.HelperEnum;
using YunusovComponentsLibrary.OfficePackage.HelperModels;
using YunusovComponentsLibrary.OfficePackage.Implements;
namespace YunusovComponentsLibrary
{
public partial class WordDocumentTable : Component
{
private Document _document = null;
private Body _body = null;
private DocumentFormat.OpenXml.Wordprocessing.Table _table = null;
private Document Document
{
get
{
if (_document == null)
{
_document = new Document();
}
return _document;
}
}
private Body Body
{
get
{
if (_body == null)
{
_body = Document.AppendChild(new Body());
}
return _body;
}
}
private DocumentFormat.OpenXml.Wordprocessing.Table Table
{
get
{
if (_table == null)
{
_table = new DocumentFormat.OpenXml.Wordprocessing.Table();
}
return _table;
}
}
public WordDocumentTable()
{
InitializeComponent();
}
public WordDocumentTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateTable<T>(WordTableWithData<T> config)
{
config.CheckFields();
config.ColumnsRowsDataCount = (config.Data.Count + 2, config.ColumnsRowsWidth.Count);
CreateHeader(config.Title);
CreateTableWithHeader();
CreateMultiHeader(config);
var array = new string[config.Data.Count, config.Headers.Count];
for (var j = 0; j < config.Data.Count; j++)
{
for (var i = 0; i < config.Headers.Count; i++)
{
(int, int, string, string) first = (0, 0, null, null)!;
foreach (var x in config.Headers.Where(x => x.ColumnIndex == i))
{
first = x;
break;
}
var (_, _, _, name) = first;
if (name != null)
{
object? value = config.Data[j]?.GetType().GetProperty(name)!.GetValue(config.Data[j], null);
array[j, i] = value == null
? config.NullReplace
: value.ToString();
}
}
}
LoadDataToTableWithMultiHeader(array);
SaveDoc(config.FileName);
}
public void SaveDoc(string filepath)
{
if (string.IsNullOrEmpty(filepath))
{
throw new ArgumentNullException("Имя файла не задано");
}
if (_document == null || _body == null)
{
throw new ArgumentNullException("Документ не сформирован, сохранять нечего");
}
if (_table != null)
{
Body.Append(Table);
}
using WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document);
MainDocumentPart mainDocumentPart = wordprocessingDocument.AddMainDocumentPart();
mainDocumentPart.Document = Document;
}
public void LoadDataToTableWithMultiHeader(string[,] data)
{
for (int i = 0; i < data.GetLength(0); i++)
{
TableRow tablerow = new TableRow();
for (int j = 0; j < data.GetLength(1); j++)
{
TableCell tableCell = new TableCell();
tableCell.Append(new Paragraph(new Run(new Text(data[i, j]))));
tablerow.Append(tableCell);
}
Table.Append(tablerow);
}
}
public void CreateMultiHeader<T>(WordTableWithData<T> config)
{
if (config.Headers == null || !config.Headers.Any())
return;
TableProperties tblProperties = new TableProperties(
new TableWidth { Type = TableWidthUnitValues.Dxa, Width = "5000" });
Table.AppendChild(tblProperties);
TableRow headerRow = new TableRow();
foreach (var header in config.Headers.Where(h => h.ColumnIndex >= 0))
{
TableCell cell = new TableCell(new Paragraph(new Run(new Text(header.Header))));
TableCellProperties cellProperties = new TableCellProperties(
new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = (header.ColumnIndex * 100).ToString() });
cell.AppendChild(cellProperties);
headerRow.AppendChild(cell);
}
Table.AppendChild(headerRow);
}
public void CreateTableWithHeader()
{
Table.AppendChild(new TableProperties(new TableBorders(new TopBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = (UInt32Value)12u
}, new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = (UInt32Value)12u
}, new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = (UInt32Value)12u
}, new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = (UInt32Value)12u
}, new InsideHorizontalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = (UInt32Value)12u
}, new InsideVerticalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = (UInt32Value)12u
})));
}
public void CreateHeader(string header)
{
Paragraph paragraph = Body.AppendChild(new Paragraph());
Run run = paragraph.AppendChild(new Run());
run.AppendChild(new RunProperties(new Bold()));
run.AppendChild(new Text(header));
}
}
}

View File

@ -5,6 +5,18 @@
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Version>$(VersionPrefix)1.0.2</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspose.Words" Version="24.10.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
<PackageReference Include="Microsoft.Office.Interop.Excel" Version="15.0.4795.1001" />
<PackageReference Include="Microsoft.Office.Interop.Word" Version="15.0.4797.1004" />
<PackageReference Include="OxyPlot.Core" Version="2.2.0" />
<PackageReference Include="OxyPlot.WindowsForms" Version="2.2.0" />
<PackageReference Include="OxyPlot.Wpf" Version="2.2.0" />
</ItemGroup>
</Project>