Compare commits

...

2 Commits

Author SHA1 Message Date
abazov73
9431261a10 Added excel table component 2023-10-15 18:07:28 +04:00
abazov73
8364484ce7 Added excel image component 2023-10-15 15:18:36 +04:00
10 changed files with 506 additions and 0 deletions

View File

@ -28,6 +28,7 @@
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.abazovCheckedListBox = new AbazovViewComponents.Components.AbazovCheckedListBox();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonClear = new System.Windows.Forms.Button();
@ -42,6 +43,11 @@
this.buttonGetValue = new System.Windows.Forms.Button();
this.buttonGetIndex = new System.Windows.Forms.Button();
this.buttonSetIndex = new System.Windows.Forms.Button();
this.excelImagesComponent = new AbazovViewComponents.LogicalComponents.ExcelImagesComponent(this.components);
this.buttonExcelImages = new System.Windows.Forms.Button();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.buttonExcelTable = new System.Windows.Forms.Button();
this.excelTableComponent = new AbazovViewComponents.LogicalComponents.ExcelTableComponent(this.components);
this.SuspendLayout();
//
// abazovCheckedListBox
@ -91,6 +97,7 @@
this.abazovDatePicker.Name = "abazovDatePicker";
this.abazovDatePicker.Size = new System.Drawing.Size(275, 48);
this.abazovDatePicker.TabIndex = 4;
this.abazovDatePicker.Value = null;
this.abazovDatePicker.DateChange += new System.Action<System.DateTime>(this.abazovDatePicker_DateChange);
this.abazovDatePicker.AutoSizeChanged += new System.EventHandler(this.abazovDatePicker_DateChange);
//
@ -182,11 +189,39 @@
this.buttonSetIndex.UseVisualStyleBackColor = true;
this.buttonSetIndex.Click += new System.EventHandler(this.buttonSetIndex_Click);
//
// buttonExcelImages
//
this.buttonExcelImages.Location = new System.Drawing.Point(12, 327);
this.buttonExcelImages.Name = "buttonExcelImages";
this.buttonExcelImages.Size = new System.Drawing.Size(150, 29);
this.buttonExcelImages.TabIndex = 14;
this.buttonExcelImages.Text = "Excel (картинки)";
this.buttonExcelImages.UseVisualStyleBackColor = true;
this.buttonExcelImages.Click += new System.EventHandler(this.buttonExcelImages_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "Изображения|*.png;*.jpg;";
this.openFileDialog.Multiselect = true;
this.openFileDialog.Title = "Выберте изображения";
//
// buttonExcelTable
//
this.buttonExcelTable.Location = new System.Drawing.Point(168, 327);
this.buttonExcelTable.Name = "buttonExcelTable";
this.buttonExcelTable.Size = new System.Drawing.Size(128, 29);
this.buttonExcelTable.TabIndex = 15;
this.buttonExcelTable.Text = "Excel (Таблица)";
this.buttonExcelTable.UseVisualStyleBackColor = true;
this.buttonExcelTable.Click += new System.EventHandler(this.buttonExcelTable_Click);
//
// FormTest
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(850, 450);
this.Controls.Add(this.buttonExcelTable);
this.Controls.Add(this.buttonExcelImages);
this.Controls.Add(this.buttonSetIndex);
this.Controls.Add(this.buttonGetIndex);
this.Controls.Add(this.buttonGetValue);
@ -223,5 +258,10 @@
private Button buttonGetValue;
private Button buttonGetIndex;
private Button buttonSetIndex;
private AbazovViewComponents.LogicalComponents.ExcelImagesComponent excelImagesComponent;
private Button buttonExcelImages;
private OpenFileDialog openFileDialog;
private Button buttonExcelTable;
private AbazovViewComponents.LogicalComponents.ExcelTableComponent excelTableComponent;
}
}

View File

@ -1,11 +1,13 @@
using AbazovViewComponents.Components;
using AbazovViewComponents.Exceptions;
using AbazovViewComponents.LogicalComponents;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
@ -127,5 +129,41 @@ namespace AbazovAppView
{
abazovTreeView.SelectedNodeIndex = 0;
}
private void buttonExcelImages_Click(object sender, EventArgs e)
{
var res = openFileDialog.ShowDialog(this);
if (res != DialogResult.OK) return;
var files = openFileDialog.FileNames;
openFileDialog.Dispose();
List<Bitmap> images = new List<Bitmap>();
string path = AppDomain.CurrentDomain.BaseDirectory + "test.xlsx";
MessageBox.Show(path);
if (excelImagesComponent.createWithImages(new ExcelImageInfo(path, "Header", files))) MessageBox.Show("Успех!");
else MessageBox.Show("Ошибка, проверьте консоль");
}
private void buttonExcelTable_Click(object sender, EventArgs e)
{
List<OfficeWorker> workers = new List<OfficeWorker>();
workers.Add(new OfficeWorker(1, "Иванов", "Иван", 20, "Отдел продаж", "Бухгалтер", 25, "+7(834)234-03-49"));
workers.Add(new OfficeWorker(1, "Петров", "Петр", 25, "Отдел продаж", "Менеджер", 20, "+7(834)123-03-49"));
workers.Add(new OfficeWorker(1, "Сидоров", "Сергей", 27, "Отдел кадров", "HR", 2, "+7(834)593-03-49", true));
string path = AppDomain.CurrentDomain.BaseDirectory + "test.xlsx";
List<(int, int)> merges = new List<(int, int)>();
merges.Add((1, 3));
merges.Add((4, 6));
List<int> heights = Enumerable.Repeat(20, 9).ToList();
List<(string, string)> headers = new List<(string, string)> { ("id", "id"), ("", "Личные данные"),
("lastName", "Фамилия"), ("firstName", "Имя"),
("age", "Возраст"), ("", "Работа"),
("department", "Отдел"), ("position", "Должность"),
("boxNumber", "Номер бокса"), ("phoneNumber", "Телефон"),
("isInVacation", "В отпуске"), };
if (excelTableComponent.createWithTable(path, "test", merges, heights, headers, workers)) MessageBox.Show("Успех");
}
}
}

View File

@ -57,4 +57,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="excelImagesComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>233, 17</value>
</metadata>
<metadata name="excelTableComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>392, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbazovAppView
{
public class OfficeWorker
{
public OfficeWorker(int id, string lastName, string firstName, int age, string department, string position, int boxNumber, string phoneNumber, bool isInVacation = false)
{
this.id = id;
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
this.department = department;
this.position = position;
this.boxNumber = boxNumber;
this.phoneNumber = phoneNumber;
this.isInVacation = isInVacation;
}
public int id;
public string lastName;
public string firstName;
public int age;
public string department;
public string position;
public int boxNumber;
public string phoneNumber;
public bool isInVacation;
}
}

View File

@ -7,4 +7,27 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<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>
<Private>true</Private>
</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>
<Private>true</Private>
</COMReference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbazovViewComponents.LogicalComponents
{
public class ExcelImageInfo
{
public ExcelImageInfo(string path, string title, string[] imagePaths)
{
this.path = path;
this.title = title;
this.imagePaths = imagePaths;
}
public string path;
public string title;
public string[] imagePaths;
}
}

View File

@ -0,0 +1,36 @@
namespace AbazovViewComponents.LogicalComponents
{
partial class ExcelImagesComponent
{
/// <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,74 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
namespace AbazovViewComponents.LogicalComponents
{
public partial class ExcelImagesComponent : Component
{
public ExcelImagesComponent()
{
InitializeComponent();
}
public ExcelImagesComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public bool createWithImages(ExcelImageInfo info)
{
var excelApp = new Microsoft.Office.Interop.Excel.Application { SheetsInNewWorkbook = 1 };
Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
try
{
//create
Worksheet worksheet = (Worksheet)workbook.Worksheets.get_Item(1);
//header
var excelcells = worksheet.get_Range("A1", "D1");
excelcells.Merge(Type.Missing);
excelcells.Font.Bold = true;
excelcells.Font.Size = 14;
excelcells.Font.Name = "Times New Roman";
excelcells.ColumnWidth = 8;
excelcells.RowHeight = 25;
excelcells.HorizontalAlignment = Constants.xlCenter;
excelcells.VerticalAlignment = Constants.xlCenter;
excelcells.Value2 = info.title;
int topOffset = 25;
foreach (string path in info.imagePaths)
{
Bitmap bm = new Bitmap(path);
worksheet.Shapes.AddPicture2(path, MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, topOffset, bm.Width, bm.Height, MsoPictureCompress.msoPictureCompressFalse);
topOffset += bm.Height;
bm.Dispose();
}
//save
object missing = System.Reflection.Missing.Value;
workbook.SaveAs(info.path, XlFileFormat.xlOpenXMLWorkbook, missing, missing, false, false, XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlUserResolution, true, missing, missing, missing);
workbook.Close();
excelApp.Quit();
return true;
}
catch (Exception)
{
workbook.Close();
excelApp.Quit();
return false;
}
}
}
}

View File

@ -0,0 +1,36 @@
namespace AbazovViewComponents.LogicalComponents
{
partial class ExcelTableComponent
{
/// <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,194 @@
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AbazovViewComponents.LogicalComponents
{
public partial class ExcelTableComponent : Component
{
public ExcelTableComponent()
{
InitializeComponent();
}
public ExcelTableComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
private string GetExcelColumnName(int columnNumber)
{
string columnName = "";
while (columnNumber > 0)
{
int modulo = (columnNumber - 1) % 26;
columnName = Convert.ToChar('A' + modulo) + columnName;
columnNumber = (columnNumber - modulo) / 26;
}
return columnName;
}
public bool createWithTable<T>(string path, string title, List<(int, int)> merges, List<int> heights, List<(string, string)> headers, List<T> items)
{
if (merges.Count == 0 || heights.Count == 0 || headers.Count == 0 || items.Count == 0) throw new ArgumentException("Недостаточно данных");
int[] cellsArray = new int[heights.Count];
foreach (var merge in merges)
{
if (merge.Item1 >= merge.Item2) throw new ArgumentException("Неправильно заполнены объединения строк");
for (int i = merge.Item1; i < merge.Item2; i++)
{
cellsArray[i]++;
}
}
foreach (int cell in cellsArray)
{
if (cell > 1) throw new ArgumentException("Объединения заходят друг на друга");
}
var excelApp = new Microsoft.Office.Interop.Excel.Application { SheetsInNewWorkbook = 1 };
Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
try
{
//create
Worksheet worksheet = (Worksheet)workbook.Worksheets.get_Item(1);
//header
var excelcells = worksheet.get_Range("A1", "A1");
excelcells.Font.Bold = true;
excelcells.Font.Size = 14;
excelcells.Font.Name = "Times New Roman";
excelcells.ColumnWidth = 8;
excelcells.RowHeight = 25;
excelcells.HorizontalAlignment = Constants.xlCenter;
excelcells.VerticalAlignment = Constants.xlCenter;
excelcells.Value2 = title;
//checks
List<Microsoft.Office.Interop.Excel.Range> ranges = new List<Microsoft.Office.Interop.Excel.Range>();
foreach (var merge in merges)
{
ranges.Add(worksheet.get_Range("A" + (merge.Item1 + 2), "A" + (merge.Item2 + 2)));
}
int rangeIndex = 0;
int headerIndex = 0;
List<FieldInfo> cellFields = new List<FieldInfo>();
var type = typeof(T);
for (int i = 0; i < heights.Count; i++)
{
if (cellsArray[i] == 1)
{
//work with merge
if (!string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
var groupRange = ranges[rangeIndex];
groupRange.Merge(Type.Missing);
groupRange.Font.Bold = true;
groupRange.Font.Size = 14;
groupRange.Font.Name = "Times New Roman";
groupRange.ColumnWidth = 20;
groupRange.HorizontalAlignment = Constants.xlCenter;
groupRange.VerticalAlignment = Constants.xlCenter;
groupRange.Value2 = headers[headerIndex].Item2;
headerIndex++;
//work with cells in merge
for (; i <= merges[rangeIndex].Item2; i++)
{
//work with cell
if (string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
var field = type.GetField(headers[headerIndex].Item1);
if (field == null) throw new ArgumentException("В заголовках указано поле, которого нет в переданном классе");
//format header
var range = worksheet.get_Range("B" + (i + 2), "B" + (i + 2));
range.Font.Bold = true;
range.Font.Size = 14;
range.Font.Name = "Times New Roman";
range.ColumnWidth = 20;
range.RowHeight = heights[i];
range.HorizontalAlignment = Constants.xlCenter;
range.VerticalAlignment = Constants.xlCenter;
range.Value2 = headers[headerIndex].Item2;
cellFields.Add(field);
headerIndex++;
}
i--;
rangeIndex++;
}
else
{
//work with cell
if (string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
var field = type.GetField(headers[headerIndex].Item1);
if (field == null) throw new ArgumentException("В заголовках указано поле, которого нет в переданном классе");
//format header
var range = worksheet.get_Range("A" + (i + 2), "B" + (i + 2));
range.Merge(Type.Missing);
range.Font.Bold = true;
range.Font.Size = 14;
range.Font.Name = "Times New Roman";
range.ColumnWidth = 40;
range.RowHeight = heights[i];
range.HorizontalAlignment = Constants.xlCenter;
range.VerticalAlignment = Constants.xlCenter;
range.Value2 = headers[headerIndex].Item2;
cellFields.Add(field);
headerIndex++;
}
}
int columnNum = 3;
foreach (T item in items)
{
string column = GetExcelColumnName(columnNum);
int rowNum = 2;
foreach (var cellField in cellFields)
{
var range = worksheet.get_Range(column + rowNum, column + rowNum);
range.Font.Size = 14;
range.Font.Name = "Times New Roman";
range.ColumnWidth = 20;
range.HorizontalAlignment = Constants.xlCenter;
range.VerticalAlignment = Constants.xlCenter;
range.Value2 = cellField.FieldType == typeof(bool) ? ((bool) cellField.GetValue(item) ? "Да" : "Нет") : cellField.GetValue(item);
rowNum++;
}
columnNum++;
}
var borderRange = worksheet.get_Range("A2", GetExcelColumnName(columnNum-1) + (headerIndex - 1));
borderRange.Borders.LineStyle = XlLineStyle.xlContinuous;
borderRange.Borders.Weight = 2d;
//save
object missing = System.Reflection.Missing.Value;
workbook.SaveAs(path, XlFileFormat.xlOpenXMLWorkbook, missing, missing, false, false, XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlUserResolution, true, missing, missing, missing);
workbook.Close();
excelApp.Quit();
return true;
}
catch (Exception ex)
{
workbook.Close();
excelApp.Quit();
throw;
}
}
}
}