82 lines
2.8 KiB
C#
82 lines
2.8 KiB
C#
using ComponentOrientedPlatform.Abstractions;
|
||
using OfficeOpenXml;
|
||
using OfficeOpenXml.Drawing.Chart;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace ReportPlugin.Excel.LineChart;
|
||
|
||
public sealed class LineChartExcelReport : IReportDocumentWithChartLineContract
|
||
{
|
||
public string DocumentFormat => "xlsx";
|
||
|
||
private List<string>? _xLabels;
|
||
public void SetCategories(List<string> labels) => _xLabels = labels;
|
||
|
||
public async Task CreateDocumentAsync(
|
||
string filePath,
|
||
string header,
|
||
string chartTitle,
|
||
Dictionary<string, List<(int Parameter, double Value)>> series)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentNullException(nameof(filePath));
|
||
if (string.IsNullOrWhiteSpace(header)) throw new ArgumentNullException(nameof(header));
|
||
if (string.IsNullOrWhiteSpace(chartTitle)) throw new ArgumentNullException(nameof(chartTitle));
|
||
if (series is null || series.Count == 0) throw new ArgumentOutOfRangeException(nameof(series));
|
||
|
||
var parameters = series.First().Value.Select(v => v.Parameter).ToArray();
|
||
foreach (var s in series.Values)
|
||
if (!parameters.SequenceEqual(s.Select(v => v.Parameter)))
|
||
throw new ArgumentException("В разных сериях различаются параметры.");
|
||
|
||
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
||
using var package = new ExcelPackage();
|
||
var ws = package.Workbook.Worksheets.Add("Диаграмма");
|
||
|
||
ws.Cells["A1"].Value = header;
|
||
ws.Cells["A1"].Style.Font.Bold = true;
|
||
ws.Cells["A1"].Style.Font.Size = 18;
|
||
|
||
ws.Cells[3, 1].Value = "Категория";
|
||
int col = 2;
|
||
foreach (var key in series.Keys)
|
||
{
|
||
ws.Cells[3, col].Value = key;
|
||
col++;
|
||
}
|
||
|
||
var labels = _xLabels ?? parameters.Select(i => $"Категория {i}").ToList();
|
||
|
||
int n = parameters.Length;
|
||
for (int i = 0; i < n; i++)
|
||
{
|
||
ws.Cells[4 + i, 1].Value = labels[i];
|
||
col = 2;
|
||
foreach (var s in series.Values)
|
||
{
|
||
ws.Cells[4 + i, col].Value = s[i].Value;
|
||
col++;
|
||
}
|
||
}
|
||
|
||
|
||
var chart = ws.Drawings.AddChart(chartTitle, eChartType.ColumnClustered) as ExcelBarChart;
|
||
chart.Title.Text = chartTitle;
|
||
chart.SetPosition(1, 0, series.Count + 2, 0);
|
||
chart.SetSize(900, 420);
|
||
|
||
var xRange = ws.Cells[4, 1, 3 + n, 1];
|
||
col = 2;
|
||
foreach (var key in series.Keys)
|
||
{
|
||
var yRange = ws.Cells[4, col, 3 + n, col];
|
||
chart.Series.Add(yRange, xRange).Header = key;
|
||
col++;
|
||
}
|
||
|
||
await package.SaveAsAsync(new FileInfo(filePath));
|
||
}
|
||
} |