2 компонент не робит(

This commit is contained in:
Татьяна Артамонова 2023-10-13 21:09:48 +04:00
parent fca28d34dd
commit d1c4275408
15 changed files with 830 additions and 7 deletions

View File

@ -7,4 +7,10 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="EPPlus" Version="6.2.10" />
<PackageReference Include="NPOI" Version="2.6.2" />
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,10 @@
namespace COP.Enums
{
public enum LegendPosition
{
Top,
Bottom,
Left,
Right
}
}

36
COP/ExcelComponent.Designer.cs generated Normal file
View File

@ -0,0 +1,36 @@
namespace COP
{
partial class ExcelComponent
{
/// <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
}
}

73
COP/ExcelComponent.cs Normal file
View File

@ -0,0 +1,73 @@
using COP.Info;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.ComponentModel;
namespace COP
{
public partial class ExcelComponent : Component
{
public ExcelComponent()
{
InitializeComponent();
}
public ExcelComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void GenerateExcelWithImages(ExcelImageInfo info)
{
if (string.IsNullOrEmpty(info.fileName))
{
throw new ArgumentNullException(nameof(info.fileName), "File name cannot be null or empty.");
}
if (info.images == null || info.images.Count == 0)
{
throw new ArgumentException("At least one image must be provided.", nameof(info.images));
}
if (string.IsNullOrEmpty(info.documentTitle))
{
throw new ArgumentNullException(nameof(info.documentTitle), "Document title cannot be null or empty.");
}
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet("Sheet1");
sheet.CreateRow(0).CreateCell(0).SetCellValue(info.documentTitle);
int startRowIndex = 2;
var rowOffset = 1;
foreach (var imageInfo in info.images)
{
using var fs = new FileStream(imageInfo.FilePath, FileMode.Open, FileAccess.Read);
var imageBytes = new byte[fs.Length];
fs.Read(imageBytes, 0, imageBytes.Length);
var pictureIdx = workbook.AddPicture(imageBytes, PictureType.JPEG);
var drawing = sheet.CreateDrawingPatriarch();
var anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, startRowIndex, 1, startRowIndex + 1);
var picture = drawing.CreatePicture(anchor, pictureIdx);
picture.Resize();
var pictureHeight = picture.GetImageDimension().Height / 20;
startRowIndex += pictureHeight + rowOffset;
}
using (var fs = new FileStream(info.fileName, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}
public class ImageInfo
{
public string? FilePath { get; set; }
}
}
}

36
COP/ExcelTable.Designer.cs generated Normal file
View File

@ -0,0 +1,36 @@
namespace COP
{
partial class ExcelTable
{
/// <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
}
}

215
COP/ExcelTable.cs Normal file
View File

@ -0,0 +1,215 @@
using COP.Info;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.ComponentModel;
using BorderStyle = NPOI.SS.UserModel.BorderStyle;
namespace COP
{
public partial class ExcelTable : Component
{
public ExcelTable()
{
InitializeComponent();
}
public ExcelTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void GenerateDocument(ExcelTableInfo info)
{
if (string.IsNullOrEmpty(info.FilePath))
{
throw new ArgumentException("File path is null or empty.");
}
if (string.IsNullOrEmpty(info.DocumentTitle))
{
throw new ArgumentException("Document title is null or empty.");
}
if (info.Data == null || info.Data.Count == 0)
{
throw new ArgumentException("Data is null or empty.");
}
// Создание документа и листа
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet("Sheet1");
// Установка заголовка документа в первой строке листа
sheet.CreateRow(0).CreateCell(0).SetCellValue(info.DocumentTitle);
int posString = 2;
int posColumn = 1;
List<string> properties = new();
foreach (var property in info.Properties)
{
if (property.Value.Item1.Count == 1)
{
var cell1 = sheet.GetRow(posString).CreateCell(posColumn);
cell1.SetCellValue(property.Key);
cell1.CellStyle.FillPattern = FillPattern.SolidForeground;
cell1.CellStyle.FillForegroundColor = HSSFColor.LightGreen.Index;
properties.Add(property.Key);
posString++;
continue;
}
var cell = sheet.GetRow(posString).CreateCell(posColumn);
cell.SetCellValue(property.Key);
cell.CellStyle.Rotation = 180;
cell.CellStyle.FillPattern = FillPattern.SolidForeground;
cell.CellStyle.FillForegroundColor = HSSFColor.Aqua.Index;
sheet.SetColumnWidth(posColumn, sheet.DefaultColumnWidth);
posColumn++;
foreach (var field in property.Value.Item1)
{
int id = property.Value.Item1.IndexOf(field);
var cellValue = sheet.GetRow(posString).CreateCell(posColumn);
cellValue.SetCellValue(field);
cellValue.CellStyle.FillPattern = FillPattern.SolidForeground;
cellValue.CellStyle.FillForegroundColor = HSSFColor.Aqua.Index;
sheet.GetRow(posString).Height = (short)property.Value.Item2[id];
properties.Add(field);
posString++;
}
posColumn--;
}
posColumn = 3;
foreach (var data in info.Data)
{
posString = 2;
var type = data.GetType();
foreach (var property in properties)
{
var cellValue = sheet.GetRow(posString).CreateCell(posColumn);
cellValue.SetCellValue((string)(type.GetField(property) == null ? type.GetProperty(property).GetValue(data) : type.GetField(property).GetValue(data)));
posString++;
}
posColumn++;
}
/*var dataCellStyle = GetDataCellStyle(workbook);
for (int row = 0; row < info.HeaderTitles.Count; row++)
{
// Создание заголовков для шапки таблицы
var headerRow = sheet.CreateRow(row + 1);
var headerCellStyle = GetHeaderCellStyle(workbook);
var cell = headerRow.CreateCell(0);
cell.SetCellValue(info.HeaderTitles[row]);
cell.CellStyle = headerCellStyle;
// Заполнение таблицы
for (int col = 0; col < info.Data.Count; col++)
{
var dataCell = headerRow.CreateCell(col + 2);
var value = GetPropertyValue(info.Data[col], row);
dataCell.SetCellValue(value.ToString());
dataCell.CellStyle = dataCellStyle;
}
}*/
// Объединение ячеек в шапке таблицы
/*for (int i = 0; i < info.MergeInfo.Count; i++)
{
var cellMergeInfo = info.MergeInfo[i];
var mergeStartCellRef = CellReference.ConvertNumToColString(cellMergeInfo.StartCol) + (cellMergeInfo.StartRow + 1);
var mergeEndCellRef = CellReference.ConvertNumToColString(cellMergeInfo.EndCol) + (cellMergeInfo.EndRow + 1);
sheet.AddMergedRegion(new CellRangeAddress(cellMergeInfo.StartRow, cellMergeInfo.EndRow, cellMergeInfo.StartCol, cellMergeInfo.EndCol));
var mergeCell = sheet.GetRow(cellMergeInfo.StartRow).CreateCell(cellMergeInfo.StartCol);
mergeCell.SetCellValue(cellMergeInfo.Value);
}*/
/*for (int row = 0; row < info.HeaderTitles.Count; row++)
{
sheet.AddMergedRegion(new CellRangeAddress(row, row, 0, 1));
foreach (var merge in info.MergeInfo)
if (merge.Value != "")
{
sheet.RemoveMergedRegion(row)
}
foreach (var mergedRegion in mergedRegions)
{
sheet.RemoveMergedRegion(mergedRegion);
}
}*/
/*foreach (var merge in info.MergeInfo)
{
for (int row = 0; row < info.HeaderTitles.Count; row++)
{
if (merge.Value != "")
{
var valueCell = sheet.GetRow(row + 1).GetCell(0);
valueCell.SetCellValue(merge.Value);
sheet.AddMergedRegion(new CellRangeAddress(merge.StartRow, merge.EndRow, merge.StartCol, merge.EndCol));
}
else
{
sheet.AddMergedRegion(new CellRangeAddress(merge.StartRow, merge.EndRow, 0, 1));
}
}
}*/
/*// Задание высоты строк
for (int i = 0; i < info.MergeInfo.Count; i++)
{
var row = sheet.GetRow(i);
if (row != null)
{
row.Height = (short)(info.MergeInfo[i].RowHeight * 20);
}
}*/
using var fs = new FileStream(info.FilePath, FileMode.Create, FileAccess.Write);
workbook.Write(fs);
}
private static object GetPropertyValue(object obj, int columnIndex)
{
var properties = obj.GetType().GetProperties();
var field = properties[columnIndex];
return field.GetValue(obj);
}
private static ICellStyle GetHeaderCellStyle(IWorkbook workbook)
{
var style = workbook.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
var font = workbook.CreateFont();
font.Boldweight = (short)FontBoldWeight.Bold;
style.SetFont(font);
return style;
}
private static ICellStyle GetDataCellStyle(IWorkbook workbook)
{
var style = workbook.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
return style;
}
}
}

8
COP/Info/DataItem.cs Normal file
View File

@ -0,0 +1,8 @@
namespace COP.Info
{
public class DataItem
{
public string Name { get; set; } = string.Empty;
public double Value { get; set; }
}
}

View File

@ -0,0 +1,22 @@
using COP.Enums;
namespace COP.Info
{
public class ExcelChartInfo
{
public string? filePath { get; set; } = string.Empty;
public string? documentTitle { get; set; } = string.Empty;
public string? chartTitle { get; set; } = string.Empty;
public LegendPosition legendPosition { get; set; }
public List<DataItem>? data { get; set; }
public ExcelChartInfo(string? filePath, string? documentTitle, string? chartTitle, LegendPosition legendPosition, List<DataItem>? data)
{
this.filePath = filePath;
this.documentTitle = documentTitle;
this.chartTitle = chartTitle;
this.legendPosition = legendPosition;
this.data = data;
}
}
}

View File

@ -0,0 +1,18 @@
using static COP.ExcelComponent;
namespace COP.Info
{
public class ExcelImageInfo
{
public string? fileName { get; set; } = string.Empty;
public string? documentTitle { get; set; } = string.Empty;
public List<ImageInfo>? images { get; set; }
public ExcelImageInfo (string? fileName, string? documentTitle, List<ImageInfo>? images)
{
this.fileName = fileName;
this.documentTitle = documentTitle;
this.images = images;
}
}
}

View File

@ -0,0 +1,77 @@
namespace COP.Info
{
public class ExcelTableInfo
{
public string? FilePath { get; set; } = string.Empty;
public string? DocumentTitle { get; set; } = string.Empty;
public List<object>? Data { get; set; } = new();
public Dictionary<string, (List<string>, List<int>)> Properties = new();
public ExcelTableInfo(string filePath, string documentTitle, List<object> data, Dictionary<string, (List<string>, List<int>)>? properties)
{
FilePath = filePath;
DocumentTitle = documentTitle;
Data = data;
Properties = properties;
}
public void addDictionary(string name, string property, int height)
{
if (Properties.ContainsKey(name))
{
Properties[name].Item1.Add(property);
Properties[name].Item2.Add(height);
}
else
{
Properties.Add(name, (new List<string>(), new List<int>()));
Properties[name].Item1.Add(property);
Properties[name].Item2.Add(height);
}
}
public void addDictionaryAlone(string item, int height)
{
Properties.Add(item, (new List<string>(), new List<int>()));
Properties[item].Item1.Add(item);
Properties[item].Item2.Add(height);
}
/*public string FilePath { get; set; } = string.Empty;
public string DocumentTitle { get; set; } = string.Empty;
public List<MergeInfo> MergeInfo;
public List<string>? HeaderTitles;
public List<object>? Data;
public Dictionary<string, (List<string>, List<int>)> Headers { get; set; }
public void addDictionary(string name, string header, int height)
{
if (headers.ContainsKey(name))
{
headers[name].Item1.Add(header);
headers[name].Item2.Add(height);
}
else
{
headers.Add(name, (new List<string>(), new List<int>()));
headers[name].Item1.Add(header);
headers[name].Item2.Add(height);
}
}
public void addDictionaryAlone(string header, int height)
{
headers.Add(header, (new List<string>(), new List<int>()));
headers[header].Item1.Add(header);
headers[header].Item2.Add(height);
}
public ExcelTableInfo(string filePath, string documentTitle, List<MergeInfo> mergeInfo, List<string> headerTitles, List<object> data)
{
FilePath = filePath;
DocumentTitle = documentTitle;
MergeInfo = mergeInfo;
HeaderTitles = headerTitles;
Data = data;
}*/
}
}

36
COP/PieChart.Designer.cs generated Normal file
View File

@ -0,0 +1,36 @@
namespace COP
{
partial class PieChart
{
/// <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
}
}

71
COP/PieChart.cs Normal file
View File

@ -0,0 +1,71 @@
using COP.Info;
using OfficeOpenXml;
using System.ComponentModel;
using LicenseContext = OfficeOpenXml.LicenseContext;
using OfficeOpenXml.Drawing.Chart;
namespace COP
{
public partial class PieChart : Component
{
public PieChart()
{
InitializeComponent();
}
public PieChart(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void GenerateDocument(ExcelChartInfo info)
{
if (string.IsNullOrEmpty(info.filePath))
{
throw new ArgumentException("File path is null or empty.");
}
if (string.IsNullOrEmpty(info.chartTitle))
{
throw new ArgumentException("Chart title is null or empty.");
}
if (string.IsNullOrEmpty(info.documentTitle))
{
throw new ArgumentException("Document title is null or empty.");
}
if (info.data == null || info.data.Count == 0)
{
throw new ArgumentException("Data is null or empty.");
}
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using ExcelPackage excelPackage = new();
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
worksheet.Cells["A1"].Value = info.documentTitle;
int row = 2;
int startCol = 1;
int endCol = 1;
foreach (var data in info.data)
{
worksheet.Cells[row, endCol].Value = data.Name;
worksheet.Cells[row + 1, endCol].Value = data.Value;
endCol++;
}
ExcelPieChart? pieChart = worksheet.Drawings.AddChart(info.chartTitle, eChartType.Pie) as ExcelPieChart;
pieChart.Title.Text = info.chartTitle;
pieChart.Series.Add(ExcelCellBase.GetAddress(row + 1, startCol, row + 1, endCol - 1),
ExcelCellBase.GetAddress(row, startCol, row, endCol - 1));
pieChart.Legend.Position = (eLegendPosition)(int)info.legendPosition;
pieChart.DataLabel.ShowPercent = true;
pieChart.SetPosition(1, 0, 0, 0);
FileInfo fi = new(info.filePath);
excelPackage.SaveAs(fi);
}
}
}

View File

@ -28,6 +28,7 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.components = new System.ComponentModel.Container();
this.userCheckedListBox = new COP.UserCheckedListBox(); this.userCheckedListBox = new COP.UserCheckedListBox();
this.userDateTimePicker = new COP.UserDateTimePicker(); this.userDateTimePicker = new COP.UserDateTimePicker();
this.userTreeView = new COP.UserTreeView(); this.userTreeView = new COP.UserTreeView();
@ -36,6 +37,12 @@
this.buttonShowItems = new System.Windows.Forms.Button(); this.buttonShowItems = new System.Windows.Forms.Button();
this.textBoxShowDate = new System.Windows.Forms.TextBox(); this.textBoxShowDate = new System.Windows.Forms.TextBox();
this.buttonShowDate = new System.Windows.Forms.Button(); this.buttonShowDate = new System.Windows.Forms.Button();
this.excelComponent = new COP.ExcelComponent(this.components);
this.buttonSaveToExcel = new System.Windows.Forms.Button();
this.buttonSaveTable = new System.Windows.Forms.Button();
this.excelTable = new COP.ExcelTable(this.components);
this.buttonSaveChart = new System.Windows.Forms.Button();
this.pieChart = new COP.PieChart(this.components);
this.SuspendLayout(); this.SuspendLayout();
// //
// userCheckedListBox // userCheckedListBox
@ -111,11 +118,44 @@
this.buttonShowDate.UseVisualStyleBackColor = true; this.buttonShowDate.UseVisualStyleBackColor = true;
this.buttonShowDate.Click += new System.EventHandler(this.ButtonShowDate_Click); this.buttonShowDate.Click += new System.EventHandler(this.ButtonShowDate_Click);
// //
// buttonSaveToExcel
//
this.buttonSaveToExcel.Location = new System.Drawing.Point(236, 240);
this.buttonSaveToExcel.Name = "buttonSaveToExcel";
this.buttonSaveToExcel.Size = new System.Drawing.Size(158, 23);
this.buttonSaveToExcel.TabIndex = 8;
this.buttonSaveToExcel.Text = "Сохранить картинки";
this.buttonSaveToExcel.UseVisualStyleBackColor = true;
this.buttonSaveToExcel.Click += new System.EventHandler(this.buttonSaveToExcel_Click);
//
// buttonSaveTable
//
this.buttonSaveTable.Location = new System.Drawing.Point(412, 240);
this.buttonSaveTable.Name = "buttonSaveTable";
this.buttonSaveTable.Size = new System.Drawing.Size(158, 23);
this.buttonSaveTable.TabIndex = 9;
this.buttonSaveTable.Text = "Сохранить таблицу";
this.buttonSaveTable.UseVisualStyleBackColor = true;
this.buttonSaveTable.Click += new System.EventHandler(this.buttonSaveTable_Click);
//
// buttonSaveChart
//
this.buttonSaveChart.Location = new System.Drawing.Point(318, 269);
this.buttonSaveChart.Name = "buttonSaveChart";
this.buttonSaveChart.Size = new System.Drawing.Size(158, 23);
this.buttonSaveChart.TabIndex = 10;
this.buttonSaveChart.Text = "Сохранить диаграмму";
this.buttonSaveChart.UseVisualStyleBackColor = true;
this.buttonSaveChart.Click += new System.EventHandler(this.buttonSaveChart_Click);
//
// FormTestComponents // FormTestComponents
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(657, 321); this.ClientSize = new System.Drawing.Size(657, 321);
this.Controls.Add(this.buttonSaveChart);
this.Controls.Add(this.buttonSaveTable);
this.Controls.Add(this.buttonSaveToExcel);
this.Controls.Add(this.buttonShowDate); this.Controls.Add(this.buttonShowDate);
this.Controls.Add(this.textBoxShowDate); this.Controls.Add(this.textBoxShowDate);
this.Controls.Add(this.buttonShowItems); this.Controls.Add(this.buttonShowItems);
@ -141,5 +181,11 @@
private Button buttonShowItems; private Button buttonShowItems;
private TextBox textBoxShowDate; private TextBox textBoxShowDate;
private Button buttonShowDate; private Button buttonShowDate;
private COP.ExcelComponent excelComponent;
private Button buttonSaveToExcel;
private Button buttonSaveTable;
private COP.ExcelTable excelTable;
private Button buttonSaveChart;
private COP.PieChart pieChart;
} }
} }

View File

@ -1,4 +1,11 @@
namespace TestComponents using COP;
using COP.Enums;
using COP.Info;
using DocumentFormat.OpenXml.EMMA;
using System.ComponentModel;
using static COP.ExcelComponent;
namespace TestComponents
{ {
public partial class FormTestComponents : Form public partial class FormTestComponents : Form
{ {
@ -51,12 +58,12 @@
private void UserTreeView_Load(object sender, EventArgs e) private void UserTreeView_Load(object sender, EventArgs e)
{ {
List<Employee> employees = new List<Employee> List<Employee1> employees = new()
{ {
new Employee { Department = "Отдел1", Position = олжность1", Name = "Сотрудник1" }, new Employee1 { Department = "Отдел1", Position = олжность1", Name = "Сотрудник1" },
new Employee { Department = "Отдел2", Position = олжность2", Name = "Сотрудник2" }, new Employee1 { Department = "Отдел2", Position = олжность2", Name = "Сотрудник2" },
new Employee { Department = "Отдел1", Position = олжность1", Name = "Сотрудник3" }, new Employee1 { Department = "Отдел1", Position = олжность1", Name = "Сотрудник3" },
new Employee { Department = "Отдел2", Position = олжность3", Name = "Сотрудник4" }, new Employee1 { Department = "Отдел2", Position = олжность3", Name = "Сотрудник4" },
}; };
var Hierarchy = new List<string> { "Department", "Position", "Name" }; var Hierarchy = new List<string> { "Department", "Position", "Name" };
foreach (var prop in employees[0].GetType().GetProperties()) foreach (var prop in employees[0].GetType().GetProperties())
@ -74,11 +81,164 @@
} }
} }
public class Employee public class Employee1
{ {
public string? Department { get; set; } public string? Department { get; set; }
public string? Position { get; set; } public string? Position { get; set; }
public string? Name { get; set; } public string? Name { get; set; }
} }
private void buttonSaveToExcel_Click(object sender, EventArgs e)
{
ExcelComponent excel = new();
List<ImageInfo> images = new()
{
new ImageInfo() { FilePath = "C:\\Users\\User\\Documents\\image1.jpg" },
new ImageInfo() { FilePath = "C:\\Users\\User\\Documents\\image2.jpg" },
new ImageInfo() { FilePath = "C:\\Users\\User\\Documents\\image3.jpg" }
};
ExcelImageInfo info = new("C:\\Users\\User\\Documents\\test.xlsx", "My Document", images);
try
{
excel.GenerateExcelWithImages(info);
MessageBox.Show("Сохарнено успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public class Sportsmen
{
public string name;
public string sport;
public string city;
public string country;
public string Region { get { return city; } set { city = value; } }
public string awards;
public Sportsmen(string name, string sport, string city, string country, string awards)
{
this.name = name;
this.sport = sport;
this.city = city;
this.country = country;
this.awards = awards;
}
public Sportsmen() { }
public override string ToString()
{
return country + " " + city + " " + name + " " + sport + " " + awards;
}
}
string[] names = { "Vova M", "Sasha A", "Dima D", "Danila L" };
string[] sports = { "Run", "Swim", "Cycle", "Race", "Box" };
string[] cities = { "Moskow", "Samara", "Piter", "Kazan", "Kyrsk" };
string[] countries = { "Russia", "Spain", "China", "India", "Brazil" };
string[] rewards = { "#1", "#2", "KMS", "Olymp", "MS" };
List<Employee> sportsmens = new();
private void buttonSaveTable_Click(object sender, EventArgs e)
{
ExcelTable table = new();
string path = @"C:\\Users\\User\\Documents\\testtable.xlsx";
string title = "title";
var dataList = new List<object>
{
new Employee { Id = 1, Status = "Active", Name = "John", Surname = "Doe", Age = "30", Department = "IT", Position = "Manager" },
new Employee { Id = 2, Status = "Active", Name = "Jane", Surname = "Smith", Age = "35", Department = "Design", Position = "Senior" },
};
var info = new ExcelTableInfo(path, "Sample Document", new List<object>(), new Dictionary<string, (List<string>, List<int>)>());
info.addDictionary("Table1", "Field1", 20);
info.addDictionary("Table1", "Field2", 15);
info.addDictionary("Table2", "Field1", 25);
info.addDictionary("Table2", "Field2", 18);
info.addDictionary("Table2", "Field3", 22);
info.addDictionaryAlone("Table3", 30);
info.Data.Add(new Employee1 { Department = "Dept1", Position = "Position1", Name = "Employee1" });
info.Data.Add(new Employee1 { Department = "Dept2", Position = "Position2", Name = "Employee2" });
info.Data.Add(new Employee1 { Department = "Dept1", Position = "Position1", Name = "Employee3" });
dataList.Clear();
try
{
table.GenerateDocument(info);
MessageBox.Show("Сохарнено успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
/*ExcelTable table = new();
var mergeInfo = new List<MergeInfo>
{
new MergeInfo { Value = "", StartRow = 0, EndRow = 0, StartCol = 0, EndCol = 1 },
new MergeInfo { Value = "", StartRow = 1, EndRow = 1, StartCol = 0, EndCol = 1 },
new MergeInfo { Value = "Личные данные", StartRow = 2, EndRow = 4, StartCol = 0, EndCol = 0 },
new MergeInfo { Value = "Работа", StartRow = 5, EndRow = 6, StartCol = 0, EndCol = 0 }
};
var headerTitles = new List<string> { "ID", "Status", "Name", "Surname", "Age", "Department", "Position" };
var data = new List<object>
{
new Employees { Id = 1, Status = "Active", Name = "John", Surname = "Doe", Age = "30", Department = "IT", Position = "Manager" },
new Employees { Id = 2, Status = "Active", Name = "Jane", Surname = "Smith", Age = "35", Department = "Design", Position = "Senior" },
};
ExcelTableInfo info = new("C:\\Users\\User\\Documents\\testtable.xlsx", "My Document", mergeInfo, headerTitles, data);
try
{
table.GenerateDocument(info);
MessageBox.Show("Сохарнено успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}*/
}
public class Employee
{
public int? Id { get; set; }
public string? Status { get; set; } = string.Empty;
public string? Name { get; set; } = string.Empty;
public string? Surname { get; set; } = string.Empty;
public string? Age { get; set; } = string.Empty;
public string? Department { get; set; } = string.Empty;
public string? Position { get; set; } = string.Empty;
}
private void buttonSaveChart_Click(object sender, EventArgs e)
{
PieChart chart = new();
LegendPosition legend = new();
var data = new List<DataItem>()
{
new DataItem() { Name = "Data 1", Value = 10 },
new DataItem() { Name = "Data 2", Value = 20 },
new DataItem() { Name = "Data 3", Value = 30 },
new DataItem() { Name = "Data 4", Value = 40 }
};
ExcelChartInfo info = new("C:\\Users\\User\\Documents\\testchart.xlsx", "My Document", "My Chart", legend, data);
try
{
chart.GenerateDocument(info);
MessageBox.Show("Сохарнено успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} }
} }

View File

@ -57,4 +57,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="excelComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="excelTable.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>160, 17</value>
</metadata>
<metadata name="pieChart.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>268, 17</value>
</metadata>
</root> </root>