Compare commits
5 Commits
3c960c8ccb
...
b78f933bd7
Author | SHA1 | Date | |
---|---|---|---|
b78f933bd7 | |||
e1d5ffe478 | |||
cbc470fe0f | |||
976c74f4ac | |||
bc43cb1957 |
@ -1,18 +1,6 @@
|
||||
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
|
||||
using DocumentFormat.OpenXml.Drawing;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using DocumentFormat.OpenXml;
|
||||
using Excel = Microsoft.Office.Interop.Excel;
|
||||
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
|
||||
{
|
||||
@ -28,149 +16,93 @@ 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)
|
||||
{
|
||||
// Создаем новый Excel документ
|
||||
using (SpreadsheetDocument document = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
|
||||
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)
|
||||
{
|
||||
// Добавляем WorkbookPart
|
||||
WorkbookPart workbookPart = document.AddWorkbookPart();
|
||||
workbookPart.Workbook = new Workbook();
|
||||
|
||||
// Добавляем лист
|
||||
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
|
||||
worksheetPart.Worksheet = new Worksheet(new SheetData());
|
||||
|
||||
// Добавляем таблицу стилей
|
||||
WorkbookStylesPart stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
|
||||
stylesPart.Stylesheet = CreateStylesheet();
|
||||
stylesPart.Stylesheet.Save();
|
||||
|
||||
// Добавляем информацию о листе
|
||||
Sheets sheets = document.WorkbookPart.Workbook.AppendChild(new Sheets());
|
||||
Sheet sheet = new Sheet()
|
||||
if (File.Exists(imagePath))
|
||||
{
|
||||
Id = document.WorkbookPart.GetIdOfPart(worksheetPart),
|
||||
SheetId = 1,
|
||||
Name = "Sheet1"
|
||||
};
|
||||
sheets.Append(sheet);
|
||||
Excel.Pictures pictures = (Excel.Pictures)worksheet.Pictures(System.Reflection.Missing.Value);
|
||||
Excel.Picture picture = pictures.Insert(imagePath);
|
||||
|
||||
// Получаем данные листа
|
||||
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
|
||||
picture.Left = cell.Left;
|
||||
picture.Top = cell.Top + currentTopOffset;
|
||||
|
||||
// Создаем строку с заголовком
|
||||
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));
|
||||
currentTopOffset += picture.Height;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new FileNotFoundException("Image not found at: " + imagePath);
|
||||
}
|
||||
|
||||
workbookPart.Workbook.Save();
|
||||
}
|
||||
}
|
||||
|
||||
// Метод для создания стилей
|
||||
private Stylesheet CreateStylesheet()
|
||||
private void ReleaseObject(object obj)
|
||||
{
|
||||
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()
|
||||
try
|
||||
{
|
||||
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)
|
||||
{
|
||||
drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
|
||||
worksheetDrawing = new WorksheetDrawing();
|
||||
drawingsPart.WorksheetDrawing = worksheetDrawing;
|
||||
if (obj != null)
|
||||
{
|
||||
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
|
||||
obj = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
drawingsPart = worksheetPart.DrawingsPart;
|
||||
worksheetDrawing = drawingsPart.WorksheetDrawing;
|
||||
obj = null;
|
||||
Console.WriteLine("Error releasing object: " + ex.ToString());
|
||||
}
|
||||
|
||||
// Добавляем изображение в DrawingsPart
|
||||
if (imagePath.EndsWith(".png"))
|
||||
finally
|
||||
{
|
||||
imagePart = drawingsPart.AddImagePart(ImagePartType.Png);
|
||||
GC.Collect();
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
36
WinFormSolution/Components/ComponentExcelWithPieDiagram.Designer.cs
generated
Normal file
36
WinFormSolution/Components/ComponentExcelWithPieDiagram.Designer.cs
generated
Normal file
@ -0,0 +1,36 @@
|
||||
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
|
||||
}
|
||||
}
|
159
WinFormSolution/Components/ComponentExcelWithPieDiagram.cs
Normal file
159
WinFormSolution/Components/ComponentExcelWithPieDiagram.cs
Normal file
@ -0,0 +1,159 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -7,8 +7,21 @@
|
||||
<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>
|
||||
|
133
WinFormSolution/WinFormsApp/FormNoVisual.Designer.cs
generated
133
WinFormSolution/WinFormsApp/FormNoVisual.Designer.cs
generated
@ -37,6 +37,18 @@
|
||||
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
|
||||
@ -69,24 +81,24 @@
|
||||
// listBoxImages
|
||||
//
|
||||
listBoxImages.FormattingEnabled = true;
|
||||
listBoxImages.Location = new Point(12, 78);
|
||||
listBoxImages.Location = new Point(12, 127);
|
||||
listBoxImages.Name = "listBoxImages";
|
||||
listBoxImages.Size = new Size(357, 104);
|
||||
listBoxImages.TabIndex = 3;
|
||||
//
|
||||
// buttonCreateExcelFile
|
||||
//
|
||||
buttonCreateExcelFile.Location = new Point(12, 223);
|
||||
buttonCreateExcelFile.Location = new Point(12, 272);
|
||||
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, 188);
|
||||
buttonAddImage.Location = new Point(12, 237);
|
||||
buttonAddImage.Name = "buttonAddImage";
|
||||
buttonAddImage.Size = new Size(257, 29);
|
||||
buttonAddImage.TabIndex = 5;
|
||||
@ -96,7 +108,7 @@
|
||||
//
|
||||
// buttonClearImages
|
||||
//
|
||||
buttonClearImages.Location = new Point(275, 188);
|
||||
buttonClearImages.Location = new Point(275, 237);
|
||||
buttonClearImages.Name = "buttonClearImages";
|
||||
buttonClearImages.Size = new Size(94, 29);
|
||||
buttonClearImages.TabIndex = 6;
|
||||
@ -104,11 +116,108 @@
|
||||
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(800, 446);
|
||||
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);
|
||||
Controls.Add(buttonClearImages);
|
||||
Controls.Add(buttonAddImage);
|
||||
Controls.Add(buttonCreateExcelFile);
|
||||
@ -118,6 +227,8 @@
|
||||
Controls.Add(textBoxFilePath);
|
||||
Name = "FormNoVisual";
|
||||
Text = "FormNoVisual";
|
||||
((System.ComponentModel.ISupportInitialize)dataGridViewSeries).EndInit();
|
||||
((System.ComponentModel.ISupportInitialize)numericUpDownSeriesValue).EndInit();
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
@ -132,5 +243,15 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -1,10 +1,26 @@
|
||||
namespace WinFormsApp
|
||||
using Components;
|
||||
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
|
||||
using LegendPosition = Components.ComponentExcelWithPieDiagram.LegendPosition;
|
||||
|
||||
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)
|
||||
@ -17,11 +33,11 @@
|
||||
try
|
||||
{
|
||||
componentExcelWithImage.CreateExcelWithImages(textBoxFilePath.Text, textBoxTitle.Text, list);
|
||||
MessageBox.Show("Успех");
|
||||
MessageBox.Show("Файл успешно создан", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Ошибка");
|
||||
MessageBox.Show($"Ошибка при создании файла:\n{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
@ -29,16 +45,16 @@
|
||||
{
|
||||
var filePath = string.Empty;
|
||||
|
||||
using (OpenFileDialog openFileDialog = new OpenFileDialog())
|
||||
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
|
||||
{
|
||||
openFileDialog.InitialDirectory = "d:\\tmp";
|
||||
openFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
|
||||
openFileDialog.FilterIndex = 1;
|
||||
openFileDialog.RestoreDirectory = true;
|
||||
saveFileDialog.InitialDirectory = "d:\\tmp";
|
||||
saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
|
||||
saveFileDialog.FilterIndex = 1;
|
||||
saveFileDialog.RestoreDirectory = true;
|
||||
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
filePath = openFileDialog.FileName;
|
||||
filePath = saveFileDialog.FileName;
|
||||
}
|
||||
}
|
||||
|
||||
@ -59,7 +75,7 @@
|
||||
using (OpenFileDialog openFileDialog = new OpenFileDialog())
|
||||
{
|
||||
openFileDialog.InitialDirectory = "d:\\tmp";
|
||||
openFileDialog.Filter = "All files (*.*)|*.*";
|
||||
openFileDialog.Filter = "Image files (*.jpeg;*.jpg;*.png)|*.jpeg;*.jpg;*.png|All files (*.*)|*.*";
|
||||
openFileDialog.FilterIndex = 1;
|
||||
openFileDialog.RestoreDirectory = true;
|
||||
|
||||
@ -79,5 +95,53 @@
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -120,4 +120,7 @@
|
||||
<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>
|
Loading…
Reference in New Issue
Block a user