PIbd-31_PotapovNS_COP_20/WinFormSolution/Components/ComponentExcelWithPieDiagram.cs

130 lines
4.5 KiB
C#
Raw Normal View History

using System.ComponentModel;
using Excel = Microsoft.Office.Interop.Excel;
namespace Components
{
public partial class ComponentExcelWithPieDiagram : Component
{
public ComponentExcelWithPieDiagram()
{
InitializeComponent();
}
public ComponentExcelWithPieDiagram(IContainer container) : this()
{
container.Add(this);
}
// Перечисление для расположения легенды
public enum LegendPosition
{
Top,
Bottom,
Left,
Right
}
// Класс для хранения данных серии
public class ChartData
{
public string SeriesName { get; set; }
public double SeriesValue { get; set; }
}
public void CreateExcelWithPieChart(
string filePath,
string fileTitle,
string chartTitle,
LegendPosition legendPosition,
List<ChartData> data)
{
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
// Устанавливаем заголовок файла
worksheet.Cells[1, 1] = fileTitle;
// Вставляем данные в таблицу для построения диаграммы
int dataStartRow = 3; // Начальная строка для данных
for (int i = 0; i < data.Count; i++)
{
worksheet.Cells[dataStartRow + i, 1] = data[i].SeriesName;
worksheet.Cells[dataStartRow + i, 2] = data[i].SeriesValue;
}
// Создание круговой диаграммы
Excel.ChartObjects chartObjects = (Excel.ChartObjects)worksheet.ChartObjects();
Excel.ChartObject chartObject = chartObjects.Add(300, 50, 400, 300); // Размер и позиция диаграммы
Excel.Chart chart = chartObject.Chart;
// Устанавливаем тип диаграммы "Круговая"
chart.ChartType = Excel.XlChartType.xlPie;
// Устанавливаем диапазон данных для диаграммы
Excel.Range chartRange = worksheet.get_Range("A3", $"B{dataStartRow + data.Count - 1}");
chart.SetSourceData(chartRange);
// Устанавливаем заголовок диаграммы
chart.HasTitle = true;
chart.ChartTitle.Text = chartTitle;
// Устанавливаем расположение легенды
SetLegendPosition(chart, legendPosition);
// Сохраняем файл
workbook.SaveAs(filePath);
workbook.Close();
excelApp.Quit();
ReleaseObject(worksheet);
ReleaseObject(workbook);
ReleaseObject(excelApp);
}
// Метод для установки позиции легенды на диаграмме
private void SetLegendPosition(Excel.Chart chart, LegendPosition legendPosition)
{
chart.HasLegend = true;
switch (legendPosition)
{
case LegendPosition.Top:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionTop;
break;
case LegendPosition.Bottom:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionBottom;
break;
case LegendPosition.Left:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionLeft;
break;
case LegendPosition.Right:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionRight;
break;
}
}
// Освобождение объектов
private void ReleaseObject(object obj)
{
try
{
if (obj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception ex)
{
obj = null;
Console.WriteLine("Error releasing object: " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}