работает третий компонент, а второй не работает

This commit is contained in:
Елена Бакальская 2024-10-22 12:40:57 +04:00
parent e2e42acf98
commit db33928447
8 changed files with 481 additions and 13 deletions

View File

@ -33,6 +33,8 @@
bigTextWordNoVisibleComponent = new UserComponentsOption19.BigTextWordNoVisibleComponent(components);
tableWordNoVisibleComponent = new UserComponentsOption19.TableWordNoVisibleComponent(components);
buttonSaveTableToWord = new Button();
diagramWordNoVisibleComponent1 = new UserComponentsOption19.DiagramWordNoVisibleComponent(components);
buttonSaveDiagram = new Button();
SuspendLayout();
//
// buttonSaveBigTextToWord
@ -55,11 +57,22 @@
buttonSaveTableToWord.UseVisualStyleBackColor = true;
buttonSaveTableToWord.Click += buttonSaveTableToWord_Click;
//
// buttonSaveDiagram
//
buttonSaveDiagram.Location = new Point(12, 142);
buttonSaveDiagram.Name = "buttonSaveDiagram";
buttonSaveDiagram.Size = new Size(270, 29);
buttonSaveDiagram.TabIndex = 2;
buttonSaveDiagram.Text = "Сохранить диаграмму в ворд :>";
buttonSaveDiagram.UseVisualStyleBackColor = true;
buttonSaveDiagram.Click += buttonSaveDiagram_Click;
//
// FormTestNoVisibleComponents
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(433, 383);
Controls.Add(buttonSaveDiagram);
Controls.Add(buttonSaveTableToWord);
Controls.Add(buttonSaveBigTextToWord);
Name = "FormTestNoVisibleComponents";
@ -73,5 +86,7 @@
private UserComponentsOption19.BigTextWordNoVisibleComponent bigTextWordNoVisibleComponent;
private UserComponentsOption19.TableWordNoVisibleComponent tableWordNoVisibleComponent;
private Button buttonSaveTableToWord;
private UserComponentsOption19.DiagramWordNoVisibleComponent diagramWordNoVisibleComponent1;
private Button buttonSaveDiagram;
}
}

View File

@ -1,4 +1,6 @@
namespace TestAppForCheckComponentsWorking
using UserComponentsOption19;
namespace TestAppForCheckComponentsWorking
{
public partial class FormTestNoVisibleComponents : Form
{
@ -104,5 +106,46 @@
public double Bonus { get; set; }
}
private void buttonSaveDiagram_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
string title = "ХОБА давай знакомиться! :D";
var chartData = new List<DiagramWordNoVisibleComponent.ChartSeries>
{
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Серия 1",
Data = new List<double> { 10, 20, 30, 40, 50 }
},
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Серия 2",
Data = new List<double> { 15, 25, 35, 45, 55 }
},
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Серия 3",
Data = new List<double> { 20, 30, 40, 50, 60 }
}
};
diagramWordNoVisibleComponent1.CreateDocumentWithChart(filePath, title, "Diagram", DiagramWordNoVisibleComponent.LegendPosition.Bottom,
chartData);
MessageBox.Show("Успешно :D проверяй скорее наличие файла...");
}
}
}
}
}

View File

@ -123,4 +123,7 @@
<metadata name="tableWordNoVisibleComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>300, 17</value>
</metadata>
<metadata name="diagramWordNoVisibleComponent1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>568, 17</value>
</metadata>
</root>

View File

@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34714.143
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UserComponentsOption19", "UserComponentsOption19\UserComponentsOption19.csproj", "{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UserComponentsOption19", "UserComponentsOption19\UserComponentsOption19.csproj", "{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestAppForCheckComponentsWorking", "TestAppForCheckComponentsWorking\TestAppForCheckComponentsWorking.csproj", "{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestAppForCheckComponentsWorking", "TestAppForCheckComponentsWorking\TestAppForCheckComponentsWorking.csproj", "{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

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

@ -0,0 +1,325 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
namespace UserComponentsOption19
{
public partial class DiagramWordNoVisibleComponent : Component
{
public DiagramWordNoVisibleComponent()
{
InitializeComponent();
}
public DiagramWordNoVisibleComponent(IContainer container) : this()
{
container.Add(this);
}
// Перечисление для позиции легенды
public enum LegendPosition
{
Top,
Bottom,
Left,
Right
}
// Класс для представления серии данных
public class ChartSeries
{
public string? Name { get; set; }
public List<double>? Data { get; set; }
}
// Основной метод для создания документа с диаграммой
public void CreateDocumentWithChart(string fileName, string documentTitle, string chartTitle, LegendPosition legendPosition, List<ChartSeries> chartData)
{
// Проверка входных данных
if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(documentTitle) || chartData == null || chartData.Count == 0)
{
throw new ArgumentException("Некорректные входные данные: проверьте имя файла, заголовок документа и наличие данных для диаграммы.");
}
// Создаем Word документ
var wordApp = new Word.Application();
var document = wordApp.Documents.Add();
wordApp.Visible = false; // Скрыть приложение Word
// Добавляем заголовок документа
var titleRange = document.Range();
titleRange.Text = documentTitle;
titleRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
titleRange.Font.Size = 14; // Размер шрифта для заголовка
titleRange.InsertParagraphAfter();
// Создаём Excel для диаграммы
var excelApp = new Excel.Application();
var workbook = excelApp.Workbooks.Add();
var worksheet = (Excel.Worksheet)workbook.Worksheets[1];
// Заполняем данные для диаграммы
int seriesCount = chartData.Count;
int dataCount = chartData[0].Data.Count;
// Заголовки серий
for (int i = 0; i < seriesCount; i++)
{
worksheet.Cells[1, i + 1] = chartData[i].Name; // Заполнение заголовков
for (int j = 0; j < dataCount; j++)
{
worksheet.Cells[j + 2, i + 1] = chartData[i].Data[j]; // Заполнение данных
}
}
// Создание диаграммы
var chartObject = (Excel.ChartObject)worksheet.ChartObjects().Add(100, 100, 300, 200);
var chart = chartObject.Chart;
chart.SetSourceData(worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[dataCount + 1, seriesCount]]);
chart.ChartType = Excel.XlChartType.xlLine; // Линейная диаграмма
chart.HasTitle = true;
chart.ChartTitle.Text = chartTitle;
// Установка позиции легенды
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;
}
//// Экспорт диаграммы в PNG
//string chartPath = Path.Combine(Path.GetTempPath(), "chart.png");
//chart.Export(chartPath, "PNG", false);
// Теперь вставляем изображение в документ Word
//var paragraph = document.Content.Paragraphs.Add();
//paragraph.Range.InlineShapes.AddChart2(chart);
// Копирование диаграммы в буфер обмена
chartObject.Copy();
// Вставка диаграммы в документ Word
var range = document.Content;
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
range.Paste();
// Сохраняем документ
document.SaveAs2(fileName);
document.Close();
wordApp.Quit();
// Закрываем Excel
workbook.Close(false);
excelApp.Quit();
}
}
}
//using DocumentFormat.OpenXml.Drawing.Charts;
//using DocumentFormat.OpenXml.Drawing.Wordprocessing;
//using DocumentFormat.OpenXml.Packaging;
//using DocumentFormat.OpenXml;
//using System.ComponentModel;
//using DocumentFormat.OpenXml.Wordprocessing;
//using Index = DocumentFormat.OpenXml.Drawing.Charts.Index;
//using DocumentFormat.OpenXml.Drawing;
//DocumentFormat.OpenXml.Drawing.Charts.Index chartIndex = new DocumentFormat.OpenXml.Drawing.Charts.Index();
//namespace UserComponentsOption19
//{
// public partial class DiagramWordNoVisibleComponent : Component
// {
// public DiagramWordNoVisibleComponent()
// {
// InitializeComponent();
// }
// public DiagramWordNoVisibleComponent(IContainer container) : this()
// {
// container.Add(this);
// }
// // Перечисление для позиции легенды
// public enum LegendPosition
// {
// Top,
// Bottom,
// Left,
// Right
// }
// // Класс для представления серии данных
// public class ChartSeries
// {
// public string? Name { get; set; }
// public List<double>? Data { get; set; }
// }
// // Основной метод для создания документа с диаграммой
// public void CreateDocumentWithChart(string fileName, string documentTitle, string chartTitle, LegendPosition legendPosition, List<ChartSeries> chartData)
// {
// // Проверка входных данных
// if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(documentTitle) || chartData == null || chartData.Count == 0)
// {
// throw new ArgumentException("Некорректные входные данные: проверьте имя файла, заголовок документа и наличие данных для диаграммы.");
// }
// // Создаем Word документ
// using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
// {
// // Основная часть документа
// MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// mainPart.Document = new Document();
// Body body = new Body();
// // Добавляем заголовок документа
// DocumentFormat.OpenXml.Drawing.Paragraph titleParagraph = CreateTitle(documentTitle);
// body.AppendChild(titleParagraph);
// // Добавляем диаграмму в документ
// ChartPart chartPart = mainPart.AddNewPart<ChartPart>();
// GenerateChart(chartPart, chartTitle, legendPosition, chartData);
// // Вставляем диаграмму в документ
// Drawing chartDrawing = CreateChartDrawing(chartPart);
// DocumentFormat.OpenXml.Drawing.Paragraph chartParagraph = new DocumentFormat.OpenXml.Drawing.Paragraph(new DocumentFormat.OpenXml.Drawing.Run(chartDrawing));
// body.AppendChild(chartParagraph);
// mainPart.Document.Append(body);
// mainPart.Document.Save();
// }
// }
// // Метод для генерации заголовка документа
// private DocumentFormat.OpenXml.Drawing.Paragraph CreateTitle(string documentTitle)
// {
// var titleParagraph = new DocumentFormat.OpenXml.Drawing.Paragraph(new DocumentFormat.OpenXml.Drawing.Run(new DocumentFormat.OpenXml.Drawing.Text(documentTitle)));
// titleParagraph.ParagraphProperties = new DocumentFormat.OpenXml.Drawing.ParagraphProperties(new Justification { Val = JustificationValues.Center });
// return titleParagraph;
// }
// // Метод для создания диаграммы
// private void GenerateChart(ChartPart chartPart, string chartTitle, LegendPosition legendPosition, List<ChartSeries> chartData)
// {
// ChartSpace chartSpace = new ChartSpace();
// DocumentFormat.OpenXml.Drawing.Charts.Chart chart = new DocumentFormat.OpenXml.Drawing.Charts.Chart();
// chart.Append(new Title(new ChartText(new RichText(new DocumentFormat.OpenXml.Drawing.Run(new DocumentFormat.OpenXml.Drawing.Text(chartTitle))))));
// PlotArea plotArea = new PlotArea();
// LineChart lineChart = new LineChart();
// uint index = 0;
// // Добавляем данные серий в диаграмму
// foreach (var series in chartData)
// {
// if (series.Name == null || series.Data == null || series.Data.Count == 0)
// {
// throw new ArgumentException("Некорректные данные серии.");
// }
// LineChartSeries lineChartSeries = new LineChartSeries(
// new Index { Val = index },
// new Order { Val = index },
// new SeriesText(new StringReference { Formula = new DocumentFormat.OpenXml.Drawing.Charts.Formula(series.Name) }));
// // Добавляем значения данных
// var numberLiteral = new NumberLiteral();
// numberLiteral.Append(new PointCount() { Val = (uint)series.Data.Count });
// foreach (var dataPoint in series.Data)
// {
// numberLiteral.Append(new NumericValue(dataPoint.ToString()));
// }
// lineChartSeries.Append(new DocumentFormat.OpenXml.Drawing.Charts.Values(numberLiteral));
// lineChart.Append(lineChartSeries);
// index++;
// }
// plotArea.Append(lineChart);
// chart.Append(plotArea);
// // Добавляем легенду
// Legend legend = CreateLegend(legendPosition);
// chart.Append(legend);
// chartSpace.Append(chart);
// chartPart.ChartSpace = chartSpace;
// }
// // Метод для создания легенды
// private Legend CreateLegend(LegendPosition legendPosition)
// {
// Legend legend = new Legend();
// LegendPositionValues legendPos;
// // Преобразуем наше перечисление в OpenXML значение
// switch (legendPosition)
// {
// case LegendPosition.Top:
// legendPos = LegendPositionValues.Top;
// break;
// case LegendPosition.Bottom:
// legendPos = LegendPositionValues.Bottom;
// break;
// case LegendPosition.Left:
// legendPos = LegendPositionValues.Left;
// break;
// case LegendPosition.Right:
// legendPos = LegendPositionValues.Right;
// break;
// default:
// throw new ArgumentOutOfRangeException(nameof(legendPosition), "Некорректная позиция легенды.");
// }
// legend.Append(new DocumentFormat.OpenXml.Drawing.Charts.LegendPosition()
// {
// Val = new EnumValue<LegendPositionValues>(legendPos)
// });
// return legend;
// }
// // Метод для вставки диаграммы в документ
// private Drawing CreateChartDrawing(ChartPart chartPart)
// {
// return new Drawing(
// new Inline(
// new Extent() { Cx = 5486400, Cy = 3200400 },
// new EffectExtent()
// {
// LeftEdge = 0L,
// TopEdge = 0L,
// RightEdge = 0L,
// BottomEdge = 0L
// },
// new DocProperties() { Id = (UInt32Value)1U, Name = "Chart 1" },
// new Graphic(
// new GraphicData(
// new ChartReference() { Id = chartPart.GetIdOfPart(chartPart) })
// { Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" })
// )
// { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U }
// );
// }
// }
//}

View File

@ -128,7 +128,22 @@ namespace UserComponentsOption19
Type objectType = typeof(T);
string selString = selectedString;
string tempString = _templateString;
string tempString =
_templateString;
List<string> arraySubstrings = new List<string>();
List<string> arrayPropertyNames = new List<string>();

View File

@ -1,14 +1,45 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<COMReference Include="Microsoft.Office.Core">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>8</VersionMinor>
<VersionMajor>2</VersionMajor>
<Guid>2df8d04c-5bfa-101b-bde5-00aa0044de52</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
<COMReference Include="Microsoft.Office.Interop.Word">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>7</VersionMinor>
<VersionMajor>8</VersionMajor>
<Guid>00020905-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
<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>