Morozov_Pibd-32_KOP/VisEl/UnvisableComponents/ExcelChart.cs
2023-10-13 17:33:04 +03:00

77 lines
2.8 KiB
C#

using OfficeOpenXml.Style;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LicenseContext = OfficeOpenXml.LicenseContext;
using OfficeOpenXml.Drawing.Chart;
namespace UnvisableComponents
{
public partial class ExcelChart : Component
{
public ExcelChart()
{
InitializeComponent();
}
public ExcelChart(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void Load(ChartInfo info)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
Check(info);
List<string> fields = new List<string>();
using (ExcelPackage excelPackage = new ExcelPackage())
{
excelPackage.Workbook.Properties.Author = "Qawithexperts";
excelPackage.Workbook.Properties.Title = "test Excel";
excelPackage.Workbook.Properties.Subject = "Write in Excel";
excelPackage.Workbook.Properties.Created = DateTime.Now;
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
worksheet.Cells["A1"].Value = info.Title;
int posString = 2;
int endColumn = 1;
int startColumn = 1;
foreach(var step in info.Dates)
{
worksheet.Cells[posString,endColumn].Value = step.Item1;
worksheet.Cells[posString+1, endColumn].Value = step.Item2;
endColumn++;
}
ExcelPieChart pieChart = worksheet.Drawings.AddChart("pieChart", eChartType.Pie3D) as ExcelPieChart;
pieChart.Title.Text = info.DiagrammTitle;
pieChart.Series.Add(ExcelRange.GetAddress(posString+1, startColumn, posString + 1, endColumn-1), ExcelRange.GetAddress(posString, startColumn, posString, endColumn-1));
pieChart.Legend.Position = (eLegendPosition)(int)info.DirLegend;
pieChart.DataLabel.ShowPercent = true;
pieChart.SetPosition(1, 0, 0, 0);
FileInfo fi = new FileInfo(info.Path);
excelPackage.SaveAs(fi);
}
}
public void Check(ChartInfo info)
{
if (string.IsNullOrEmpty(info.Title))
throw new Exception("Забыли заглавие");
if (string.IsNullOrEmpty(info.Path))
throw new Exception("Забыли путь");
if (!info.Path.EndsWith(".xlsx"))
info.Path += ".xlsx";
if (info.Dates.Count == 0)
throw new Exception("забыли данные");
}
}
}