Compare commits

..

No commits in common. "b78f933bd7045017cdcc22784960eaca44635134" and "3c960c8ccbf6d080c5664db00439784da9de2b22" have entirely different histories.

7 changed files with 160 additions and 488 deletions

View File

@ -1,6 +1,18 @@
using Excel = Microsoft.Office.Interop.Excel;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System.ComponentModel;
using Fonts = DocumentFormat.OpenXml.Spreadsheet.Fonts;
using Font = DocumentFormat.OpenXml.Spreadsheet.Font;
using Color = DocumentFormat.OpenXml.Spreadsheet.Color;
using Fill = DocumentFormat.OpenXml.Spreadsheet.Fill;
using PatternFill = DocumentFormat.OpenXml.Spreadsheet.PatternFill;
using LeftBorder = DocumentFormat.OpenXml.Spreadsheet.LeftBorder;
using RightBorder = DocumentFormat.OpenXml.Spreadsheet.RightBorder;
using TopBorder = DocumentFormat.OpenXml.Spreadsheet.TopBorder;
using BottomBorder = DocumentFormat.OpenXml.Spreadsheet.BottomBorder;
namespace Components
{
@ -16,93 +28,149 @@ namespace Components
container.Add(this);
}
private void CheckInputValues(string filePath, string tableTitle, string[] imagePaths)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (string.IsNullOrEmpty(tableTitle))
{
throw new ArgumentNullException(nameof(tableTitle));
}
if (imagePaths == null)
{
throw new ArgumentNullException(nameof(imagePaths));
}
foreach (string imagePath in imagePaths)
{
if (string.IsNullOrEmpty(imagePath))
{
throw new ArgumentNullException("Image path is null");
}
}
}
public void CreateExcelWithImages(string filePath, string tableTitle, string[] imagePaths)
{
CheckInputValues(filePath, tableTitle, imagePaths);
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Add();
Excel.Worksheet worksheet = workbook.Sheets[1];
worksheet.Cells[1, 1] = tableTitle;
InsertImagesInSingleCell(worksheet, imagePaths, 2, 1);
workbook.SaveAs(filePath);
workbook.Close();
excelApp.Quit();
ReleaseObject(worksheet);
ReleaseObject(workbook);
ReleaseObject(excelApp);
}
private void InsertImagesInSingleCell(Excel.Worksheet worksheet, string[] imagePaths, int rowIndex, int columnIndex)
{
Excel.Range cell = worksheet.Cells[rowIndex, columnIndex];
double currentTopOffset = 0;
foreach (string imagePath in imagePaths)
// Создаем новый Excel документ
using (SpreadsheetDocument document = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
if (File.Exists(imagePath))
{
Excel.Pictures pictures = (Excel.Pictures)worksheet.Pictures(System.Reflection.Missing.Value);
Excel.Picture picture = pictures.Insert(imagePath);
// Добавляем WorkbookPart
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
picture.Left = cell.Left;
picture.Top = cell.Top + currentTopOffset;
// Добавляем лист
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
currentTopOffset += picture.Height;
}
else
// Добавляем таблицу стилей
WorkbookStylesPart stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = CreateStylesheet();
stylesPart.Stylesheet.Save();
// Добавляем информацию о листе
Sheets sheets = document.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet()
{
throw new FileNotFoundException("Image not found at: " + imagePath);
Id = document.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet1"
};
sheets.Append(sheet);
// Получаем данные листа
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// Создаем строку с заголовком
Row titleRow = new Row();
Cell titleCell = CreateTextCell(1, 1, tableTitle);
titleRow.Append(titleCell);
sheetData.Append(titleRow);
// Вставляем изображения в таблицу
for (int i = 0; i < imagePaths.Length; i++)
{
Row imageRow = new Row() { RowIndex = (uint)(i + 2) }; // Начинаем со 2-й строки, т.к. первая - заголовок
sheetData.Append(imageRow);
InsertImage(document, worksheetPart, imagePaths[i], (uint)(i + 2));
}
workbookPart.Workbook.Save();
}
}
private void ReleaseObject(object obj)
// Метод для создания стилей
private Stylesheet CreateStylesheet()
{
try
return new Stylesheet(
new Fonts(new Font(new FontSize() { Val = 11 }, new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }, new FontName() { Val = "Calibri" })),
new Fills(new Fill(new PatternFill() { PatternType = PatternValues.None })),
new Borders(new Border(new LeftBorder(), new RightBorder(), new TopBorder(), new BottomBorder(), new DiagonalBorder())),
new CellFormats(new CellFormat() { FontId = 0, FillId = 0, BorderId = 0, ApplyFont = true })
);
}
// Метод для создания текстовой ячейки
private Cell CreateTextCell(int columnIndex, int rowIndex, string text)
{
Cell cell = new Cell()
{
if (obj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception ex)
DataType = CellValues.String,
CellReference = GetCellReference(columnIndex, rowIndex)
};
cell.CellValue = new CellValue(text);
return cell;
}
// Метод для получения ссылки на ячейку (например, A1)
private string GetCellReference(int columnIndex, int rowIndex)
{
char columnLetter = (char)('A' + columnIndex - 1);
return $"{columnLetter}{rowIndex}";
}
// Метод для вставки изображения в ячейку
private void InsertImage(SpreadsheetDocument document, WorksheetPart worksheetPart, string imagePath, uint rowIndex)
{
DrawingsPart drawingsPart;
ImagePart imagePart;
WorksheetDrawing worksheetDrawing;
// Проверяем, существует ли уже часть с чертежами (DrawingsPart)
if (worksheetPart.DrawingsPart == null)
{
obj = null;
Console.WriteLine("Error releasing object: " + ex.ToString());
drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetDrawing = new WorksheetDrawing();
drawingsPart.WorksheetDrawing = worksheetDrawing;
}
finally
else
{
GC.Collect();
drawingsPart = worksheetPart.DrawingsPart;
worksheetDrawing = drawingsPart.WorksheetDrawing;
}
// Добавляем изображение в DrawingsPart
if (imagePath.EndsWith(".png"))
{
imagePart = drawingsPart.AddImagePart(ImagePartType.Png);
}
else if (imagePath.EndsWith(".jpg") || imagePath.EndsWith(".jpeg"))
{
imagePart = drawingsPart.AddImagePart(ImagePartType.Jp2);
}
else
{
imagePart = drawingsPart.AddImagePart(ImagePartType.Jpeg);
}
using (FileStream stream = new FileStream(imagePath, FileMode.Open))
{
imagePart.FeedData(stream);
}
var imageId = drawingsPart.GetIdOfPart(imagePart);
// Размеры изображения
var extents = new Extents() { Cx = 990000L, Cy = 792000L }; // Пример размеров
// Якорь для изображения
var twoCellAnchor = new TwoCellAnchor(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("0"), new ColumnOffset("0"), new RowId((rowIndex - 1).ToString()), new RowOffset("0")),
new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("1"), new ColumnOffset("0"), new RowId(rowIndex.ToString()), new RowOffset("0")),
new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureProperties(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = (UInt32Value)1U, Name = "Picture 1" },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualPictureDrawingProperties()),
new DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill(
new DocumentFormat.OpenXml.Drawing.Blip() { Embed = imageId },
new DocumentFormat.OpenXml.Drawing.Stretch(new DocumentFormat.OpenXml.Drawing.FillRectangle())),
new DocumentFormat.OpenXml.Drawing.Spreadsheet.ShapeProperties(
new DocumentFormat.OpenXml.Drawing.Transform2D(new DocumentFormat.OpenXml.Drawing.Offset() { X = 0, Y = 0 }, extents),
new DocumentFormat.OpenXml.Drawing.PresetGeometry(new DocumentFormat.OpenXml.Drawing.AdjustValueList()) { Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle })
),
new ClientData()
);
worksheetDrawing.Append(twoCellAnchor);
worksheetPart.Worksheet.Save();
}
}
}

View File

@ -1,36 +0,0 @@
namespace Components
{
partial class ComponentExcelWithPieDiagram
{
/// <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

@ -1,159 +0,0 @@
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
{
[DisplayName("Серия")]
public string SeriesName { get; set; }
[DisplayName("Значение")]
public double SeriesValue { get; set; }
}
private void CheckInputValues(
string filePath,
string fileTitle,
string chartTitle,
LegendPosition legendPosition,
List<ChartData> data)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (string.IsNullOrEmpty(fileTitle))
{
throw new ArgumentNullException(nameof(fileTitle));
}
if (string.IsNullOrEmpty(chartTitle))
{
throw new ArgumentNullException(nameof(chartTitle));
}
double chartSum = 0;
foreach (var item in data)
{
if (!string.IsNullOrEmpty(item.SeriesName)) { chartSum += item.SeriesValue; }
else
{
throw new ArgumentNullException("Series name is null or empty");
}
if (item.SeriesValue == 0 || item.SeriesValue > 100)
{
throw new ArgumentOutOfRangeException("Series value is out of range");
}
}
if (chartSum > 100)
{
throw new ArgumentOutOfRangeException("Series values sum is out of range");
}
}
public void CreateExcelWithPieChart(
string filePath,
string fileTitle,
string chartTitle,
LegendPosition legendPosition,
List<ChartData> data)
{
CheckInputValues(filePath, fileTitle, chartTitle, legendPosition, 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();
}
}
}
}

View File

@ -7,21 +7,8 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<COMReference Include="Microsoft.Office.Interop.Excel">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>9</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>00020813-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
</ItemGroup>
</Project>

View File

@ -37,18 +37,6 @@
buttonCreateExcelFile = new Button();
buttonAddImage = new Button();
buttonClearImages = new Button();
componentExcelWithPieDiagram = new Components.ComponentExcelWithPieDiagram(components);
dataGridViewSeries = new DataGridView();
textBoxSeriesName = new TextBox();
numericUpDownSeriesValue = new NumericUpDown();
buttonAddSeries = new Button();
buttonClearSeries = new Button();
buttonCreateExcelWithPieDiagram = new Button();
comboBoxLegendPosition = new ComboBox();
labelLegendPosition = new Label();
textBoxDiagramTitle = new TextBox();
((System.ComponentModel.ISupportInitialize)dataGridViewSeries).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSeriesValue).BeginInit();
SuspendLayout();
//
// textBoxFilePath
@ -81,24 +69,24 @@
// listBoxImages
//
listBoxImages.FormattingEnabled = true;
listBoxImages.Location = new Point(12, 127);
listBoxImages.Location = new Point(12, 78);
listBoxImages.Name = "listBoxImages";
listBoxImages.Size = new Size(357, 104);
listBoxImages.TabIndex = 3;
//
// buttonCreateExcelFile
//
buttonCreateExcelFile.Location = new Point(12, 272);
buttonCreateExcelFile.Location = new Point(12, 223);
buttonCreateExcelFile.Name = "buttonCreateExcelFile";
buttonCreateExcelFile.Size = new Size(357, 29);
buttonCreateExcelFile.TabIndex = 4;
buttonCreateExcelFile.Text = "Создать Excel файл с картинкой";
buttonCreateExcelFile.Text = "Создать Excel файл";
buttonCreateExcelFile.UseVisualStyleBackColor = true;
buttonCreateExcelFile.Click += buttonCreateExcelFile_Click;
//
// buttonAddImage
//
buttonAddImage.Location = new Point(12, 237);
buttonAddImage.Location = new Point(12, 188);
buttonAddImage.Name = "buttonAddImage";
buttonAddImage.Size = new Size(257, 29);
buttonAddImage.TabIndex = 5;
@ -108,7 +96,7 @@
//
// buttonClearImages
//
buttonClearImages.Location = new Point(275, 237);
buttonClearImages.Location = new Point(275, 188);
buttonClearImages.Name = "buttonClearImages";
buttonClearImages.Size = new Size(94, 29);
buttonClearImages.TabIndex = 6;
@ -116,108 +104,11 @@
buttonClearImages.UseVisualStyleBackColor = true;
buttonClearImages.Click += buttonClearImages_Click;
//
// dataGridViewSeries
//
dataGridViewSeries.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewSeries.Enabled = false;
dataGridViewSeries.Location = new Point(406, 10);
dataGridViewSeries.MultiSelect = false;
dataGridViewSeries.Name = "dataGridViewSeries";
dataGridViewSeries.ReadOnly = true;
dataGridViewSeries.RowHeadersVisible = false;
dataGridViewSeries.RowHeadersWidth = 51;
dataGridViewSeries.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewSeries.Size = new Size(300, 115);
dataGridViewSeries.TabIndex = 7;
//
// textBoxSeriesName
//
textBoxSeriesName.Location = new Point(406, 166);
textBoxSeriesName.Name = "textBoxSeriesName";
textBoxSeriesName.PlaceholderText = "Название серии";
textBoxSeriesName.Size = new Size(200, 27);
textBoxSeriesName.TabIndex = 8;
//
// numericUpDownSeriesValue
//
numericUpDownSeriesValue.DecimalPlaces = 2;
numericUpDownSeriesValue.Increment = new decimal(new int[] { 1, 0, 0, 65536 });
numericUpDownSeriesValue.Location = new Point(406, 199);
numericUpDownSeriesValue.Name = "numericUpDownSeriesValue";
numericUpDownSeriesValue.Size = new Size(125, 27);
numericUpDownSeriesValue.TabIndex = 9;
numericUpDownSeriesValue.TextAlign = HorizontalAlignment.Right;
//
// buttonAddSeries
//
buttonAddSeries.Location = new Point(612, 166);
buttonAddSeries.Name = "buttonAddSeries";
buttonAddSeries.Size = new Size(94, 29);
buttonAddSeries.TabIndex = 10;
buttonAddSeries.Text = "Добавить";
buttonAddSeries.UseVisualStyleBackColor = true;
buttonAddSeries.Click += buttonAddSeries_Click;
//
// buttonClearSeries
//
buttonClearSeries.Location = new Point(537, 199);
buttonClearSeries.Name = "buttonClearSeries";
buttonClearSeries.Size = new Size(169, 29);
buttonClearSeries.TabIndex = 11;
buttonClearSeries.Text = "Очистить данные";
buttonClearSeries.UseVisualStyleBackColor = true;
buttonClearSeries.Click += buttonClearSeries_Click;
//
// buttonCreateExcelWithPieDiagram
//
buttonCreateExcelWithPieDiagram.Location = new Point(406, 272);
buttonCreateExcelWithPieDiagram.Name = "buttonCreateExcelWithPieDiagram";
buttonCreateExcelWithPieDiagram.Size = new Size(300, 29);
buttonCreateExcelWithPieDiagram.TabIndex = 12;
buttonCreateExcelWithPieDiagram.Text = "Создать Excel файл с диаграммой";
buttonCreateExcelWithPieDiagram.UseVisualStyleBackColor = true;
buttonCreateExcelWithPieDiagram.Click += buttonCreateExcelWithPieDiagram_Click;
//
// comboBoxLegendPosition
//
comboBoxLegendPosition.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxLegendPosition.FormattingEnabled = true;
comboBoxLegendPosition.Location = new Point(581, 234);
comboBoxLegendPosition.Name = "comboBoxLegendPosition";
comboBoxLegendPosition.Size = new Size(125, 28);
comboBoxLegendPosition.TabIndex = 13;
//
// labelLegendPosition
//
labelLegendPosition.AutoSize = true;
labelLegendPosition.Location = new Point(406, 237);
labelLegendPosition.Name = "labelLegendPosition";
labelLegendPosition.Size = new Size(177, 20);
labelLegendPosition.TabIndex = 14;
labelLegendPosition.Text = "Расположение легенды:";
//
// textBoxDiagramTitle
//
textBoxDiagramTitle.Location = new Point(406, 131);
textBoxDiagramTitle.Name = "textBoxDiagramTitle";
textBoxDiagramTitle.PlaceholderText = "Заголовок диаграммы";
textBoxDiagramTitle.Size = new Size(300, 27);
textBoxDiagramTitle.TabIndex = 15;
//
// FormNoVisual
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1054, 446);
Controls.Add(textBoxDiagramTitle);
Controls.Add(labelLegendPosition);
Controls.Add(comboBoxLegendPosition);
Controls.Add(buttonCreateExcelWithPieDiagram);
Controls.Add(buttonClearSeries);
Controls.Add(buttonAddSeries);
Controls.Add(numericUpDownSeriesValue);
Controls.Add(textBoxSeriesName);
Controls.Add(dataGridViewSeries);
ClientSize = new Size(800, 446);
Controls.Add(buttonClearImages);
Controls.Add(buttonAddImage);
Controls.Add(buttonCreateExcelFile);
@ -227,8 +118,6 @@
Controls.Add(textBoxFilePath);
Name = "FormNoVisual";
Text = "FormNoVisual";
((System.ComponentModel.ISupportInitialize)dataGridViewSeries).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownSeriesValue).EndInit();
ResumeLayout(false);
PerformLayout();
}
@ -243,15 +132,5 @@
private Button buttonCreateExcelFile;
private Button buttonAddImage;
private Button buttonClearImages;
private Components.ComponentExcelWithPieDiagram componentExcelWithPieDiagram;
private DataGridView dataGridViewSeries;
private TextBox textBoxSeriesName;
private NumericUpDown numericUpDownSeriesValue;
private Button buttonAddSeries;
private Button buttonClearSeries;
private Button buttonCreateExcelWithPieDiagram;
private ComboBox comboBoxLegendPosition;
private Label labelLegendPosition;
private TextBox textBoxDiagramTitle;
}
}

View File

@ -1,26 +1,10 @@
using Components;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using LegendPosition = Components.ComponentExcelWithPieDiagram.LegendPosition;
namespace WinFormsApp
namespace WinFormsApp
{
public partial class FormNoVisual : Form
{
private List<ComponentExcelWithPieDiagram.ChartData> _chartData;
private double _chartDataValuesSum
{
get
{
return _chartData.Sum(x => x.SeriesValue);
}
}
public FormNoVisual()
{
InitializeComponent();
_chartData = new List<ComponentExcelWithPieDiagram.ChartData>();
comboBoxLegendPosition.DataSource = Enum.GetValues(typeof(LegendPosition));
UpdateNumericUpDownSeriesValueMaximumValue();
}
private void buttonCreateExcelFile_Click(object sender, EventArgs e)
@ -33,11 +17,11 @@ namespace WinFormsApp
try
{
componentExcelWithImage.CreateExcelWithImages(textBoxFilePath.Text, textBoxTitle.Text, list);
MessageBox.Show("Файл успешно создан", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Успех");
}
catch (Exception ex)
catch (Exception)
{
MessageBox.Show($"Ошибка при создании файла:\n{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Ошибка");
}
}
@ -45,16 +29,16 @@ namespace WinFormsApp
{
var filePath = string.Empty;
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
saveFileDialog.InitialDirectory = "d:\\tmp";
saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
openFileDialog.InitialDirectory = "d:\\tmp";
openFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = saveFileDialog.FileName;
filePath = openFileDialog.FileName;
}
}
@ -75,7 +59,7 @@ namespace WinFormsApp
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "d:\\tmp";
openFileDialog.Filter = "Image files (*.jpeg;*.jpg;*.png)|*.jpeg;*.jpg;*.png|All files (*.*)|*.*";
openFileDialog.Filter = "All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
@ -95,53 +79,5 @@ namespace WinFormsApp
{
listBoxImages.Items.Clear();
}
private void buttonAddSeries_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxSeriesName.Text) || numericUpDownSeriesValue.Value == 0)
{
return;
}
ComponentExcelWithPieDiagram.ChartData chartData = new();
chartData.SeriesName = textBoxSeriesName.Text;
chartData.SeriesValue = (double)numericUpDownSeriesValue.Value;
_chartData.Add(chartData);
textBoxSeriesName.Text = string.Empty;
UpdateDataGridViewChartData();
UpdateNumericUpDownSeriesValueMaximumValue();
}
private void buttonClearSeries_Click(object sender, EventArgs e)
{
_chartData.Clear();
dataGridViewSeries.DataSource = null;
}
private void buttonCreateExcelWithPieDiagram_Click(object sender, EventArgs e)
{
LegendPosition legendPosition;
Enum.TryParse<LegendPosition>(comboBoxLegendPosition.SelectedValue.ToString(), out legendPosition);
try
{
componentExcelWithPieDiagram.CreateExcelWithPieChart(textBoxFilePath.Text, textBoxTitle.Text, textBoxDiagramTitle.Text, legendPosition, _chartData);
MessageBox.Show("Файл успешно создан", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при создании файла:\n{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpdateDataGridViewChartData()
{
dataGridViewSeries.DataSource = null;
dataGridViewSeries.DataSource = _chartData;
}
private void UpdateNumericUpDownSeriesValueMaximumValue()
{
numericUpDownSeriesValue.Maximum = (decimal)(100 - _chartDataValuesSum);
numericUpDownSeriesValue.Value = numericUpDownSeriesValue.Maximum;
}
}
}

View File

@ -120,7 +120,4 @@
<metadata name="componentExcelWithImage.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="componentExcelWithPieDiagram.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>256, 17</value>
</metadata>
</root>