Картинки не вставляются, а так все работает

This commit is contained in:
Никита Потапов 2024-10-07 00:07:33 +04:00
parent d46b592899
commit 3c960c8ccb
14 changed files with 539 additions and 430 deletions

View File

@ -1,30 +1,26 @@
using System.ComponentModel;
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
{
public partial class ComponentExcelWithImage : Component
{
private string _fileName;
public string FileName
{
set
{
if (string.IsNullOrEmpty(value))
{
return;
}
if (!value.EndsWith(".xlsx"))
{
throw new ArgumentException("Not xlsx file provided");
}
_fileName = value;
}
}
public ComponentExcelWithImage()
{
InitializeComponent();
_fileName = string.Empty;
}
public ComponentExcelWithImage(IContainer container) : this()
@ -32,28 +28,149 @@ namespace Components
container.Add(this);
}
public bool SaveToFile(string[] texts)
public void CreateExcelWithImages(string filePath, string tableTitle, string[] imagePaths)
{
CheckFileExsists();
using var writer = new StreamWriter(_fileName, true);
foreach (var text in texts)
// Создаем новый Excel документ
using (SpreadsheetDocument document = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
writer.WriteLine(text);
}
writer.Flush();
return true;
// Добавляем 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()
{
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));
}
private void CheckFileExsists()
{
if (string.IsNullOrEmpty(_fileName))
{
throw new ArgumentNullException(_fileName);
workbookPart.Workbook.Save();
}
if (!File.Exists(_fileName))
{
throw new FileNotFoundException(_fileName);
}
// Метод для создания стилей
private Stylesheet CreateStylesheet()
{
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()
{
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;
}
else
{
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,16 +0,0 @@
namespace Components.OfficePackage.Excel
{
public abstract class AbstractSaveToExcel
{
public void CreateReport(ExcelInfo info)
{
CreateExcel(info);
// todo
SaveExcel(info);
}
protected abstract void CreateExcel(ExcelInfo info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -1,11 +0,0 @@
namespace Components.OfficePackage.Excel
{
public class ExcelCellParameters
{
public string ColumnName { get; set; } = string.Empty;
public uint RowIndex { get; set; }
public string Text { get; set; } = string.Empty;
public string CellReference => $"{ColumnName}{RowIndex}";
public ExcelStyleInfoType StyleInfo { get; set; }
}
}

View File

@ -1,8 +0,0 @@
namespace Components.OfficePackage.Excel
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
}
}

View File

@ -1,9 +0,0 @@
namespace Components.OfficePackage.Excel
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -1,9 +0,0 @@
namespace Components.OfficePackage.Excel
{
public enum ExcelStyleInfoType
{
Title,
Text,
TextWithBroder
}
}

View File

@ -1,310 +0,0 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using Font = DocumentFormat.OpenXml.Spreadsheet.Font;
namespace Components.OfficePackage.Excel
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
/// <summary>
/// Настройка стилей для файла
/// </summary>
/// <param name="workbookpart"></param>
private static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
fills.Append(fill1);
fills.Append(fill2);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var rightBorder = new RightBorder()
{
Style = BorderStyleValues.Thin
};
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorder = new BottomBorder()
{
Style = BorderStyleValues.Thin
};
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U
};
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal = HorizontalAlignmentValues.Center
},
ApplyFont = true
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle = "TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle = "SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
/// <summary>
/// Получение номера стиля из типа
/// </summary>
/// <param name="styleInfo"></param>
/// <returns></returns>
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBroder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfo info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any() ? _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First() : _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
protected override void InsertCellInWorksheet(ExcelCellParameters excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
// Ищем строку, либо добавляем ее
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
// нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference = excelParams.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
// вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
protected override void MergeCells(ExcelMergeParameters excelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells mergeCells;
if (_worksheet.Elements<MergeCells>().Any())
{
mergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
protected override void SaveExcel(ExcelInfo info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Dispose();
}
}
}

View File

@ -0,0 +1,136 @@
namespace WinFormsApp
{
partial class FormNoVisual
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
componentExcelWithImage = new Components.ComponentExcelWithImage(components);
textBoxFilePath = new TextBox();
buttonSetFilePath = new Button();
textBoxTitle = new TextBox();
listBoxImages = new ListBox();
buttonCreateExcelFile = new Button();
buttonAddImage = new Button();
buttonClearImages = new Button();
SuspendLayout();
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(12, 12);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.PlaceholderText = "Путь к файлу";
textBoxFilePath.ReadOnly = true;
textBoxFilePath.Size = new Size(248, 27);
textBoxFilePath.TabIndex = 0;
//
// buttonSetFilePath
//
buttonSetFilePath.Location = new Point(275, 10);
buttonSetFilePath.Name = "buttonSetFilePath";
buttonSetFilePath.Size = new Size(94, 29);
buttonSetFilePath.TabIndex = 1;
buttonSetFilePath.Text = "Выбрать";
buttonSetFilePath.UseVisualStyleBackColor = true;
buttonSetFilePath.Click += buttonSetFilePath_Click;
//
// textBoxTitle
//
textBoxTitle.Location = new Point(12, 45);
textBoxTitle.Name = "textBoxTitle";
textBoxTitle.PlaceholderText = "Заголовок";
textBoxTitle.Size = new Size(357, 27);
textBoxTitle.TabIndex = 2;
//
// listBoxImages
//
listBoxImages.FormattingEnabled = true;
listBoxImages.Location = new Point(12, 78);
listBoxImages.Name = "listBoxImages";
listBoxImages.Size = new Size(357, 104);
listBoxImages.TabIndex = 3;
//
// buttonCreateExcelFile
//
buttonCreateExcelFile.Location = new Point(12, 223);
buttonCreateExcelFile.Name = "buttonCreateExcelFile";
buttonCreateExcelFile.Size = new Size(357, 29);
buttonCreateExcelFile.TabIndex = 4;
buttonCreateExcelFile.Text = "Создать Excel файл";
buttonCreateExcelFile.UseVisualStyleBackColor = true;
buttonCreateExcelFile.Click += buttonCreateExcelFile_Click;
//
// buttonAddImage
//
buttonAddImage.Location = new Point(12, 188);
buttonAddImage.Name = "buttonAddImage";
buttonAddImage.Size = new Size(257, 29);
buttonAddImage.TabIndex = 5;
buttonAddImage.Text = "Добавить изображение";
buttonAddImage.UseVisualStyleBackColor = true;
buttonAddImage.Click += buttonAddImage_Click;
//
// buttonClearImages
//
buttonClearImages.Location = new Point(275, 188);
buttonClearImages.Name = "buttonClearImages";
buttonClearImages.Size = new Size(94, 29);
buttonClearImages.TabIndex = 6;
buttonClearImages.Text = "Очистить";
buttonClearImages.UseVisualStyleBackColor = true;
buttonClearImages.Click += buttonClearImages_Click;
//
// FormNoVisual
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 446);
Controls.Add(buttonClearImages);
Controls.Add(buttonAddImage);
Controls.Add(buttonCreateExcelFile);
Controls.Add(listBoxImages);
Controls.Add(textBoxTitle);
Controls.Add(buttonSetFilePath);
Controls.Add(textBoxFilePath);
Name = "FormNoVisual";
Text = "FormNoVisual";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Components.ComponentExcelWithImage componentExcelWithImage;
private TextBox textBoxFilePath;
private Button buttonSetFilePath;
private TextBox textBoxTitle;
private ListBox listBoxImages;
private Button buttonCreateExcelFile;
private Button buttonAddImage;
private Button buttonClearImages;
}
}

View File

@ -0,0 +1,83 @@
namespace WinFormsApp
{
public partial class FormNoVisual : Form
{
public FormNoVisual()
{
InitializeComponent();
}
private void buttonCreateExcelFile_Click(object sender, EventArgs e)
{
string[] list = new string[listBoxImages.Items.Count];
for (int i = 0; i < listBoxImages.Items.Count; i++)
{
list[i] = listBoxImages.Items[i].ToString();
}
try
{
componentExcelWithImage.CreateExcelWithImages(textBoxFilePath.Text, textBoxTitle.Text, list);
MessageBox.Show("Успех");
}
catch (Exception)
{
MessageBox.Show("Ошибка");
}
}
private void buttonSetFilePath_Click(object sender, EventArgs e)
{
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "d:\\tmp";
openFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
}
}
if (!string.IsNullOrEmpty(filePath))
{
textBoxFilePath.Text = filePath;
}
else
{
textBoxFilePath.Text = string.Empty;
}
}
private void buttonAddImage_Click(object sender, EventArgs e)
{
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "d:\\tmp";
openFileDialog.Filter = "All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
}
}
if (!string.IsNullOrEmpty(filePath))
{
listBoxImages.Items.Add(filePath);
}
}
private void buttonClearImages_Click(object sender, EventArgs e)
{
listBoxImages.Items.Clear();
}
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="componentExcelWithImage.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -1,6 +1,6 @@
namespace WinFormsApp
{
partial class Form
partial class FormVisual
{
/// <summary>
/// Required designer variable.
@ -47,16 +47,18 @@
// userControlCheckedList
//
userControlCheckedList.BackColor = Color.Firebrick;
userControlCheckedList.Location = new Point(12, 12);
userControlCheckedList.Location = new Point(14, 16);
userControlCheckedList.Margin = new Padding(3, 5, 3, 5);
userControlCheckedList.Name = "userControlCheckedList";
userControlCheckedList.Size = new Size(168, 170);
userControlCheckedList.Size = new Size(192, 227);
userControlCheckedList.TabIndex = 0;
//
// buttonFillCheckedList
//
buttonFillCheckedList.Location = new Point(12, 202);
buttonFillCheckedList.Location = new Point(14, 269);
buttonFillCheckedList.Margin = new Padding(3, 4, 3, 4);
buttonFillCheckedList.Name = "buttonFillCheckedList";
buttonFillCheckedList.Size = new Size(75, 23);
buttonFillCheckedList.Size = new Size(86, 31);
buttonFillCheckedList.TabIndex = 1;
buttonFillCheckedList.Text = "Заполнить";
buttonFillCheckedList.UseVisualStyleBackColor = true;
@ -64,9 +66,10 @@
//
// buttonClearList
//
buttonClearList.Location = new Point(105, 202);
buttonClearList.Location = new Point(120, 269);
buttonClearList.Margin = new Padding(3, 4, 3, 4);
buttonClearList.Name = "buttonClearList";
buttonClearList.Size = new Size(75, 23);
buttonClearList.Size = new Size(86, 31);
buttonClearList.TabIndex = 2;
buttonClearList.Text = "Очистить";
buttonClearList.UseVisualStyleBackColor = true;
@ -75,59 +78,64 @@
// userControlDatePicker
//
userControlDatePicker.BackColor = Color.Orange;
userControlDatePicker.Location = new Point(273, 12);
userControlDatePicker.Location = new Point(312, 16);
userControlDatePicker.Margin = new Padding(3, 5, 3, 5);
userControlDatePicker.Name = "userControlDatePicker";
userControlDatePicker.Size = new Size(121, 50);
userControlDatePicker.Size = new Size(138, 67);
userControlDatePicker.TabIndex = 3;
//
// dateTimePickerMinDate
//
dateTimePickerMinDate.Format = DateTimePickerFormat.Short;
dateTimePickerMinDate.Location = new Point(246, 95);
dateTimePickerMinDate.Location = new Point(281, 127);
dateTimePickerMinDate.Margin = new Padding(3, 4, 3, 4);
dateTimePickerMinDate.Name = "dateTimePickerMinDate";
dateTimePickerMinDate.Size = new Size(91, 23);
dateTimePickerMinDate.Size = new Size(103, 27);
dateTimePickerMinDate.TabIndex = 4;
//
// dateTimePicker1
//
dateTimePicker1.Format = DateTimePickerFormat.Short;
dateTimePicker1.Location = new Point(343, 95);
dateTimePicker1.Location = new Point(392, 127);
dateTimePicker1.Margin = new Padding(3, 4, 3, 4);
dateTimePicker1.Name = "dateTimePicker1";
dateTimePicker1.Size = new Size(95, 23);
dateTimePicker1.Size = new Size(108, 27);
dateTimePicker1.TabIndex = 5;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(264, 77);
label1.Location = new Point(302, 103);
label1.Name = "label1";
label1.Size = new Size(52, 15);
label1.Size = new Size(66, 20);
label1.TabIndex = 6;
label1.Text = "MinDate";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(361, 77);
label2.Location = new Point(413, 103);
label2.Name = "label2";
label2.Size = new Size(54, 15);
label2.Size = new Size(69, 20);
label2.TabIndex = 7;
label2.Text = "MaxDate";
//
// userControlTreeView
//
userControlTreeView.BackColor = SystemColors.ActiveCaption;
userControlTreeView.Location = new Point(498, 12);
userControlTreeView.Location = new Point(569, 16);
userControlTreeView.Margin = new Padding(3, 5, 3, 5);
userControlTreeView.Name = "userControlTreeView";
userControlTreeView.SelectedIndex = 0;
userControlTreeView.Size = new Size(232, 320);
userControlTreeView.SelectedIndex = -1;
userControlTreeView.Size = new Size(265, 427);
userControlTreeView.TabIndex = 8;
//
// buttonFillTreeView
//
buttonFillTreeView.Location = new Point(498, 348);
buttonFillTreeView.Location = new Point(569, 464);
buttonFillTreeView.Margin = new Padding(3, 4, 3, 4);
buttonFillTreeView.Name = "buttonFillTreeView";
buttonFillTreeView.Size = new Size(75, 23);
buttonFillTreeView.Size = new Size(93, 31);
buttonFillTreeView.TabIndex = 9;
buttonFillTreeView.Text = "Заполнить";
buttonFillTreeView.UseVisualStyleBackColor = true;
@ -135,9 +143,10 @@
//
// buttonClearTreeView
//
buttonClearTreeView.Location = new Point(574, 348);
buttonClearTreeView.Location = new Point(661, 464);
buttonClearTreeView.Margin = new Padding(3, 4, 3, 4);
buttonClearTreeView.Name = "buttonClearTreeView";
buttonClearTreeView.Size = new Size(75, 23);
buttonClearTreeView.Size = new Size(86, 31);
buttonClearTreeView.TabIndex = 10;
buttonClearTreeView.Text = "Очистить";
buttonClearTreeView.UseVisualStyleBackColor = true;
@ -145,9 +154,10 @@
//
// buttonShowTreeViewNode
//
buttonShowTreeViewNode.Location = new Point(655, 348);
buttonShowTreeViewNode.Location = new Point(749, 464);
buttonShowTreeViewNode.Margin = new Padding(3, 4, 3, 4);
buttonShowTreeViewNode.Name = "buttonShowTreeViewNode";
buttonShowTreeViewNode.Size = new Size(75, 23);
buttonShowTreeViewNode.Size = new Size(86, 31);
buttonShowTreeViewNode.TabIndex = 11;
buttonShowTreeViewNode.Text = "Показать";
buttonShowTreeViewNode.UseVisualStyleBackColor = true;
@ -155,24 +165,26 @@
//
// textBoxTreeViewSelectedNodeIndex
//
textBoxTreeViewSelectedNodeIndex.Location = new Point(630, 397);
textBoxTreeViewSelectedNodeIndex.Location = new Point(720, 529);
textBoxTreeViewSelectedNodeIndex.Margin = new Padding(3, 4, 3, 4);
textBoxTreeViewSelectedNodeIndex.Name = "textBoxTreeViewSelectedNodeIndex";
textBoxTreeViewSelectedNodeIndex.Size = new Size(100, 23);
textBoxTreeViewSelectedNodeIndex.Size = new Size(114, 27);
textBoxTreeViewSelectedNodeIndex.TabIndex = 12;
//
// textBoxTreeViewSelectedObject
//
textBoxTreeViewSelectedObject.Location = new Point(31, 397);
textBoxTreeViewSelectedObject.Location = new Point(35, 529);
textBoxTreeViewSelectedObject.Margin = new Padding(3, 4, 3, 4);
textBoxTreeViewSelectedObject.Name = "textBoxTreeViewSelectedObject";
textBoxTreeViewSelectedObject.ReadOnly = true;
textBoxTreeViewSelectedObject.Size = new Size(593, 23);
textBoxTreeViewSelectedObject.Size = new Size(677, 27);
textBoxTreeViewSelectedObject.TabIndex = 13;
//
// Form
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(768, 470);
ClientSize = new Size(863, 627);
Controls.Add(textBoxTreeViewSelectedObject);
Controls.Add(textBoxTreeViewSelectedNodeIndex);
Controls.Add(buttonShowTreeViewNode);
@ -187,6 +199,7 @@
Controls.Add(buttonClearList);
Controls.Add(buttonFillCheckedList);
Controls.Add(userControlCheckedList);
Margin = new Padding(3, 4, 3, 4);
Name = "Form";
Text = "Form";
ResumeLayout(false);

View File

@ -2,9 +2,9 @@ using Components.Exceptions;
namespace WinFormsApp
{
public partial class Form : System.Windows.Forms.Form
public partial class FormVisual : Form
{
public Form()
public FormVisual()
{
InitializeComponent();
}

View File

@ -11,7 +11,7 @@ namespace WinFormsApp
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form());
Application.Run(new FormNoVisual());
}
}
}