This commit is contained in:
Artyom_Yashin 2024-10-03 15:48:44 +04:00
parent 014af5d1ec
commit 9d557bb450
14 changed files with 345 additions and 79 deletions

View File

@ -31,8 +31,13 @@ namespace Library_var_4_lab_1
{
throw new ArgumentNullException("Не все параметры введены");
}
ExcelInfo<object> info = new ExcelInfo<object>(path, header, text);
saveToExcel.WriteToFileBigText(info);
ExcelInfo<object> info = new ExcelInfo<object>()
{
FileName = path,
Title = header,
Text = text
};
saveToExcel.WriteToFileBigText<object>(info);
}
}
}

View File

@ -26,21 +26,19 @@ namespace Library_var_4_lab_1
InitializeComponent();
}
public void CreateTable<T>(string path, string header, List<ExcelMergeParameters> mergeParams, List<int> columnWidth, List<TreeNode> tableHeadres, List<T> human)
public void CreateTable<T>(string path, string header, List<TreeNode> tableHeadres, List<T> human)
{
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(header)
|| mergeParams == null || mergeParams.Count == 0
|| columnWidth == null || columnWidth.Count == 0
|| tableHeadres == null || tableHeadres.Count == 0
|| human == null || human.Count == 0)
{
throw new ArgumentNullException("Не все параметры введены");
}
ExcelInfo<T> info = new ExcelInfo<T>(path, header, new string[0]);
info.mergeParams = mergeParams;
info.columnWidth = columnWidth;
ExcelInfo<T> info = new ExcelInfo<T>();
info.FileName = path;
info.Title = header;
info.tableHeadres = tableHeadres;
info.data = human;
info.TableData = human;
saveToExcel.WriteToFileConfigurableTable(info);
}
}

View File

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

View File

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

View File

@ -0,0 +1,36 @@
namespace Library_var_4_lab_1
{
partial class LineDiagram
{
/// <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,49 @@
using Library_var_4_lab_1.OfficePackage.HelperModels;
using OfficePackage.HelperModels;
using OfficePackage.Implements;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library_var_4_lab_1
{
public partial class LineDiagram : Component
{
private LineDiagramCreation diagramCreation = new();
public LineDiagram()
{
InitializeComponent();
}
public LineDiagram(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDiagram(string path, string header, string diagramHeader, DiagramLegendLocation legendLocation, List<(string, List<(string Name, double Value)>)> data)
{
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(header)
|| string.IsNullOrEmpty(diagramHeader)
|| data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(path));
}
DiagramInfo info = new()
{
path = path,
header = header,
diagramHeader = diagramHeader,
legendLocation = legendLocation,
data = data
};
LineDiagramCreation creation = new();
creation.Create(info);
}
}
}

View File

@ -0,0 +1,64 @@
using Aspose.Cells;
using Aspose.Cells.Charts;
using Library_var_4_lab_1.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library_var_4_lab_1
{
public class LineDiagramCreation
{
Workbook workbook = new Workbook();
Worksheet worksheet;
public string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public void Create(DiagramInfo info)
{
worksheet = workbook.Worksheets[0];
worksheet.Cells["A1"].PutValue(info.header);
int rowIndex = 2;
foreach (var category in info.data[0].values)
{
worksheet.Cells[$"ZA{rowIndex}"].PutValue(category.Item1);
rowIndex++;
}
rowIndex = 2;
int columnIndex = 1;
foreach (var column in info.data)
{
worksheet.Cells[$"Z{Alphabet.ElementAt(columnIndex)}1"].PutValue(column.seriesName);
rowIndex = 2;
foreach (var row in column.values)
{
worksheet.Cells[$"Z{Alphabet.ElementAt(columnIndex)}{rowIndex}"].PutValue(row.Value);
rowIndex++;
}
columnIndex++;
}
int chartIndex = worksheet.Charts.Add(ChartType.Line, 5, 0, 15, 5);
Chart chart = worksheet.Charts[chartIndex];
chart.SetChartDataRange("ZA1:ZC4", true);
chart.Title.Text = info.diagramHeader;
switch (info.legendLocation)
{
case DiagramLegendLocation.Left:
chart.Legend.Position = LegendPositionType.Left;
break;
case DiagramLegendLocation.Right:
chart.Legend.Position = LegendPositionType.Right;
break;
case DiagramLegendLocation.Top:
chart.Legend.Position = LegendPositionType.Top;
break;
case DiagramLegendLocation.Bottom:
chart.Legend.Position = LegendPositionType.Bottom;
break;
}
workbook.Save("C:\\Users\\123\\Desktop\\Lab2_KOP2.xlsx");
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library_var_4_lab_1
{
public class LineDiagramInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string DiagramTitle { get; set; } = string.Empty;
public DiagramLegendLocation LegendLocation { get; set; } = DiagramLegendLocation.Right;
public List<Dictionary<string, List<(string Name, double Value)>>> Data { 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 (Data == null || !Data.Any())
throw new ArgumentNullException(nameof(Data), "DiagramData cannot be null or empty.");
}
}
}

View File

@ -1,4 +1,5 @@
using DocumentFormat.OpenXml.Vml;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Vml;
using DocumentFormat.OpenXml.Wordprocessing;
using OfficePackage.HelperEnums;
using OfficePackage.HelperModels;
@ -12,15 +13,16 @@ namespace OfficePackage
{
public abstract class AbstractSaveToExcel
{
public List<string> properties = new List<string>();
public string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public List<string> properties = new List<string>();
/// <summary>
/// Создание отчета
/// </summary>
/// <param name="info"></param>
public void WriteToFileBigText<T>(ExcelInfo<T> info)
{
OpenExcel(info);
OpenExcel<T>(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
@ -40,7 +42,7 @@ namespace OfficePackage
});
rowIndex++;
}
SaveExcel(info);
SaveExcel<T>(info);
}
public void WriteToFileConfigurableTable<T>(ExcelInfo<T> info)
@ -81,12 +83,28 @@ namespace OfficePackage
}
colIndex++;
}
foreach (var excelParam in info.mergeParams)
colIndex = 0;
ExcelMergeParameters mergeParams = new ExcelMergeParameters();
foreach (var column in info.tableHeadres)
{
MergeCells(excelParam);
if (column.Nodes.Count == 0)
{
mergeParams.colIndex = colIndex;
mergeParams.isHorisontel = false;
mergeParams.count = 1;
MergeCells(mergeParams);
}
if (column.Nodes.Count > 0)
{
mergeParams.colIndex = colIndex;
mergeParams.isHorisontel = true;
mergeParams.count = column.Nodes.Count;
MergeCells(mergeParams);
}
colIndex++;
}
int rowIndex = 4;
foreach (var obj in info.data)
foreach (var obj in info.TableData)
{
if (obj == null) continue;
for (int i = 0; i < properties.Count; i++)
@ -110,6 +128,18 @@ namespace OfficePackage
}
SaveExcel(info);
}
public void CreateDiagram(ExcelInfo<object> info)
{
OpenExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
}
/// <summary>
/// Создание excel-файла
/// </summary>
@ -126,6 +156,8 @@ namespace OfficePackage
/// </summary>
/// <param name="mergeParameters"></param>
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void CreateLineDiagram(ExcelInfo<object> info);
/// <summary>
/// Сохранение файла
/// </summary>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library_var_4_lab_1.OfficePackage.HelperModels
{
public class DiagramInfo
{
public string path { get; set; } = string.Empty;
public string header { get; set; } = string.Empty;
public string diagramHeader { get; set; } = string.Empty;
public DiagramLegendLocation legendLocation { get; set; } = DiagramLegendLocation.Right;
public List<(string seriesName, List<(string Name, double Value)> values)> data { get; set; } = new();
}
}

View File

@ -1,4 +1,5 @@
using System;
using Library_var_4_lab_1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -6,23 +7,26 @@ using System.Threading.Tasks;
namespace OfficePackage.HelperModels
{
public class ExcelInfo<T>
public class ExcelInfo<T>
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string[]? Text { get; set; }
public List<ExcelMergeParameters> mergeParams { get; set; }
public List<int> columnWidth { get; set; }
public List<TreeNode> tableHeadres { get; set; }
public List<T> data { get; set; }
public List<T> TableData { get; set; }
public string DiagramTitle { get; set; } = string.Empty;
public DiagramLegendLocation LegendLocation { get; set; } = DiagramLegendLocation.Right;
public List<Dictionary<string, List<(string Name, double Value)>>> DiagramData { get; set; } = new();
public ExcelInfo(string fileName, string title, string[] text )
{
FileName = fileName;
Title = title;
Text = text;
}
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 (DiagramData == null || !DiagramData.Any())
throw new ArgumentNullException(nameof(DiagramData), "DiagramData cannot be null or empty.");
}
}
}

View File

@ -12,6 +12,9 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Font = DocumentFormat.OpenXml.Spreadsheet.Font;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using Text = DocumentFormat.OpenXml.Spreadsheet.Text;
namespace OfficePackage.Implements
{
@ -132,7 +135,7 @@ namespace OfficePackage.Implements
{
Vertical = VerticalAlignmentValues.Center,
WrapText = false,
Horizontal = HorizontalAlignmentValues.Left
Horizontal = HorizontalAlignmentValues.Center
},
ApplyFont = true
};
@ -213,9 +216,9 @@ namespace OfficePackage.Implements
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart =
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart =
_spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
?
_spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
@ -229,12 +232,21 @@ namespace OfficePackage.Implements
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Columns columns = new Columns();
for (int i = 0; i < info.columnWidth.Count; i++)
{
columns.Append(new Column() { Min = (UInt32)i + 1, Max = (UInt32)i + 1, Width = info.columnWidth[i], CustomWidth = true });
if (info.tableHeadres != null)
{
Columns columns = new Columns();
for (int i = 0; i < info.tableHeadres.Count; i++)
{
if (info.tableHeadres[i].Nodes.Count == 0)
columns.Append(new Column() { Min = (UInt32)i + 1, Max = (UInt32)i + 1, Width = Convert.ToInt32(info.tableHeadres[i].Name), CustomWidth = true });
else
for (int j = 0; j < info.tableHeadres[i].Nodes.Count; j++)
{
columns.Append(new Column() { Min = (UInt32)i + 1 + (UInt32)j, Max = (UInt32)i + 1 + (UInt32)j, Width = Convert.ToInt32(info.tableHeadres[i].Nodes[j].Name), CustomWidth = true });
}
}
worksheetPart.Worksheet.AppendChild(columns);
}
worksheetPart.Worksheet.AppendChild(columns);
worksheetPart.Worksheet.AppendChild(new SheetData());
// Добавляем лист в книгу
var sheets =
@ -246,7 +258,6 @@ namespace OfficePackage.Implements
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
@ -342,27 +353,7 @@ namespace OfficePackage.Implements
_worksheet.Elements<SheetData>().First());
}
}
MergeCell mergeCell = new MergeCell();
// foreach (var excelParam in excelParams)
// {
// if (excelParam.ColumnFromName == null)
// {
// mergeCell = new MergeCell()
// {
// Reference = new StringValue(excelParam.Merge)
// };
// mergeCells.Append(mergeCell);
// }
// if (excelParam.CellFromName == string.Empty)
// {
// mergeCell = new MergeCell()
// {
// Reference = new StringValue(excelParam.MergeColumns)
// };
// }
//}
MergeCell mergeCell = new MergeCell();
if (excelParams.isHorisontel == false)
{
mergeCell = new MergeCell()
@ -380,6 +371,15 @@ namespace OfficePackage.Implements
mergeCells.Append(mergeCell);
}
}
protected override void CreateLineDiagram(ExcelInfo<object> info)
{
//LineChart chart =
//foreach (var series in info.DiagramData)
//{
// chart.
//}
}
protected override void SaveExcel<T>(ExcelInfo<T> info)
{
if (_spreadsheetDocument == null)

View File

@ -61,6 +61,7 @@
buttonWriteLinesToExcel = new Button();
configurableTable1 = new Library_var_4_lab_1.ConfigurableTable(components);
button1 = new Button();
button2 = new Button();
SuspendLayout();
//
// dropDownList1
@ -330,11 +331,22 @@
button1.UseVisualStyleBackColor = true;
button1.Click += buttonConfigTable_Click;
//
// button2
//
button2.Location = new Point(1134, 428);
button2.Name = "button2";
button2.Size = new Size(94, 29);
button2.TabIndex = 30;
button2.Text = "button2";
button2.UseVisualStyleBackColor = true;
button2.Click += buttonDiagramCreate_Click;
//
// Form1
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1350, 549);
Controls.Add(button2);
Controls.Add(button1);
Controls.Add(buttonWriteLinesToExcel);
Controls.Add(richTextBox);
@ -405,5 +417,6 @@
private Button buttonWriteLinesToExcel;
private Library_var_4_lab_1.ConfigurableTable configurableTable1;
private Button button1;
private Button button2;
}
}

View File

@ -102,40 +102,27 @@ namespace TestProj
private void buttonWriteLinesToExcel_Click(object sender, EventArgs e)
{
bigTextExcel.WriteToExcel("C:\\Users\\123\\Desktop\\Lab2_KOP1.xlsx", "Çàãîëîâîê", richTextBox.Lines);
bigTextExcel.WriteToExcel("C:\\Users\\123\\Desktop\\Lab2_KOP.xlsx", "Çàãîëîâîê", richTextBox.Lines);
}
//òàñêà 2
private void buttonConfigTable_Click(object sender, EventArgs e)
{
List<ExcelMergeParameters> mergeParameters = new();
mergeParameters.Add(new ExcelMergeParameters()
{
colIndex = 0,
isHorisontel = false
});
mergeParameters.Add(new ExcelMergeParameters()
{
colIndex = 1,
isHorisontel = true,
count = 2
});
List<int> width = new();
width.Add(20);
width.Add(20);
width.Add(50);
List<TreeNode> headers = new List<TreeNode>();
headers.Add(new TreeNode()
{
Text = "Ãðóïïà",
Tag = "Group"
Name = "20",
Tag = "Group",
});
TreeNode node1 = new();
node1.Text = "Èìÿ";
node1.Name = "20";
node1.Tag = "Name";
TreeNode node2 = new();
node2.Text = "Ôàìèëèÿ";
node2.Name = "40";
node2.Tag = "SurName";
TreeNode node3 = new();
node3.Text = "ÔÈÎ";
@ -146,8 +133,25 @@ namespace TestProj
people.Add(new Human() { Group = "ÏÈáä-33", Name = "Àðò¸ì", SurName = "ßøèí" });
people.Add(new Human() { Group = "ÏÈáä-33", Name = "Ðîñòèñëàâ", SurName = "Çàõàðîâ" });
people.Add(new Human() { Group = "ÏÈáä-33", Name = "Íèÿç", SurName = "Þíóñîâ" });
configurableTable1.CreateTable<Human>("C:\\Users\\123\\Desktop\\Lab2_KOP1.xlsx", "Çàãîëîâîê", mergeParameters, width, headers, people);
MessageBox.Show("Ãîòîâî ¸áàíà");
configurableTable1.CreateTable<Human>("C:\\Users\\123\\Desktop\\Lab2_KOP1.xlsx", "Çàãîëîâîê", headers, people);
}
public void buttonDiagramCreate_Click(object sender, EventArgs e)
{
LineDiagram lineDiagramCreation = new();
List<(string seriesName, List<(string Name, double Value)> values)> data = new();
List<(string Name, double Value)> values = new();
values.Add(("1", 30));
values.Add(("2", 40));
values.Add(("3", 60));
data.Add(("Ãðàôèê1", values));
values = new();
values.Add(("1", 60));
values.Add(("2", 40));
values.Add(("3", 30));
data.Add(("Ãðàôèê2", values));
lineDiagramCreation.CreateDiagram("C:\\Users\\123\\Desktop\\Lab2_KOP1.xlsx", "Çàãîëîâîê", "Diagram", DiagramLegendLocation.Right, data);
}
}
}