Две таски второй лабы
This commit is contained in:
parent
0b05d77cdd
commit
014af5d1ec
36
KOP_Labs/Library_var_4_lab_1/BigTextExcel.Designer.cs
generated
Normal file
36
KOP_Labs/Library_var_4_lab_1/BigTextExcel.Designer.cs
generated
Normal file
@ -0,0 +1,36 @@
|
||||
namespace Library_var_4_lab_1
|
||||
{
|
||||
partial class BigTextExcel
|
||||
{
|
||||
/// <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
|
||||
}
|
||||
}
|
38
KOP_Labs/Library_var_4_lab_1/BigTextExcel.cs
Normal file
38
KOP_Labs/Library_var_4_lab_1/BigTextExcel.cs
Normal file
@ -0,0 +1,38 @@
|
||||
using OfficePackage.HelperModels;
|
||||
using OfficePackage.Implements;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Library_var_4_lab_1
|
||||
{
|
||||
public partial class BigTextExcel : Component
|
||||
{
|
||||
SaveToExcel saveToExcel = new();
|
||||
public BigTextExcel()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public BigTextExcel(IContainer container)
|
||||
{
|
||||
container.Add(this);
|
||||
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public void WriteToExcel(string path, string header, string[] text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(header) || text == null)
|
||||
{
|
||||
throw new ArgumentNullException("Не все параметры введены");
|
||||
}
|
||||
ExcelInfo<object> info = new ExcelInfo<object>(path, header, text);
|
||||
saveToExcel.WriteToFileBigText(info);
|
||||
}
|
||||
}
|
||||
}
|
36
KOP_Labs/Library_var_4_lab_1/ConfigurableTable.Designer.cs
generated
Normal file
36
KOP_Labs/Library_var_4_lab_1/ConfigurableTable.Designer.cs
generated
Normal file
@ -0,0 +1,36 @@
|
||||
namespace Library_var_4_lab_1
|
||||
{
|
||||
partial class ConfigurableTable
|
||||
{
|
||||
/// <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
|
||||
}
|
||||
}
|
47
KOP_Labs/Library_var_4_lab_1/ConfigurableTable.cs
Normal file
47
KOP_Labs/Library_var_4_lab_1/ConfigurableTable.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using DocumentFormat.OpenXml.Drawing;
|
||||
using OfficePackage.HelperModels;
|
||||
using OfficePackage.Implements;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Library_var_4_lab_1
|
||||
{
|
||||
public partial class ConfigurableTable : Component
|
||||
{
|
||||
SaveToExcel saveToExcel = new();
|
||||
public ConfigurableTable()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public ConfigurableTable(IContainer container)
|
||||
{
|
||||
container.Add(this);
|
||||
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public void CreateTable<T>(string path, string header, List<ExcelMergeParameters> mergeParams, List<int> columnWidth, List<TreeNode> tableHeadres, List<T> human)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(header)
|
||||
|| mergeParams == null || mergeParams.Count == 0
|
||||
|| columnWidth == null || columnWidth.Count == 0
|
||||
|| tableHeadres == null || tableHeadres.Count == 0
|
||||
|| human == null || human.Count == 0)
|
||||
{
|
||||
throw new ArgumentNullException("Не все параметры введены");
|
||||
}
|
||||
ExcelInfo<T> info = new ExcelInfo<T>(path, header, new string[0]);
|
||||
info.mergeParams = mergeParams;
|
||||
info.columnWidth = columnWidth;
|
||||
info.tableHeadres = tableHeadres;
|
||||
info.data = human;
|
||||
saveToExcel.WriteToFileConfigurableTable(info);
|
||||
}
|
||||
}
|
||||
}
|
@ -7,4 +7,8 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -0,0 +1,136 @@
|
||||
using DocumentFormat.OpenXml.Vml;
|
||||
using DocumentFormat.OpenXml.Wordprocessing;
|
||||
using OfficePackage.HelperEnums;
|
||||
using OfficePackage.HelperModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OfficePackage
|
||||
{
|
||||
public abstract class AbstractSaveToExcel
|
||||
{
|
||||
public List<string> properties = new List<string>();
|
||||
public string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
/// <summary>
|
||||
/// Создание отчета
|
||||
/// </summary>
|
||||
/// <param name="info"></param>
|
||||
public void WriteToFileBigText<T>(ExcelInfo<T> info)
|
||||
{
|
||||
OpenExcel(info);
|
||||
InsertCellInWorksheet(new ExcelCellParameters
|
||||
{
|
||||
ColumnName = "A",
|
||||
RowIndex = 1,
|
||||
Text = info.Title,
|
||||
StyleInfo = ExcelStyleInfoType.Title
|
||||
});
|
||||
uint rowIndex = 3;
|
||||
foreach (string line in info.Text)
|
||||
{
|
||||
InsertCellInWorksheet(new ExcelCellParameters
|
||||
{
|
||||
ColumnName = "A",
|
||||
RowIndex = rowIndex,
|
||||
Text = line,
|
||||
StyleInfo = ExcelStyleInfoType.Text
|
||||
});
|
||||
rowIndex++;
|
||||
}
|
||||
SaveExcel(info);
|
||||
}
|
||||
|
||||
public void WriteToFileConfigurableTable<T>(ExcelInfo<T> info)
|
||||
{
|
||||
OpenExcel(info);
|
||||
InsertCellInWorksheet(new ExcelCellParameters
|
||||
{
|
||||
ColumnName = "A",
|
||||
RowIndex = 1,
|
||||
Text = info.Title,
|
||||
StyleInfo = ExcelStyleInfoType.Title
|
||||
});
|
||||
int colIndex = 0;
|
||||
foreach (var node in info.tableHeadres)
|
||||
{
|
||||
InsertCellInWorksheet(new ExcelCellParameters
|
||||
{
|
||||
ColumnName = Alphabet.ElementAt(colIndex).ToString(),
|
||||
RowIndex = 2,
|
||||
Text = node.Text,
|
||||
StyleInfo = ExcelStyleInfoType.Title
|
||||
});
|
||||
if (node.Nodes.Count == 0)
|
||||
properties.Add(node.Tag?.ToString() ?? string.Empty);
|
||||
if (node.Nodes.Count > 0)
|
||||
{
|
||||
for (int i = 0; i < node.Nodes.Count; i++)
|
||||
{
|
||||
InsertCellInWorksheet(new ExcelCellParameters
|
||||
{
|
||||
ColumnName = Alphabet.ElementAt(colIndex + i).ToString(),
|
||||
RowIndex = 3,
|
||||
Text = node.Nodes[i].Text,
|
||||
StyleInfo = ExcelStyleInfoType.Title
|
||||
});
|
||||
properties.Add(node.Nodes[i].Tag?.ToString() ?? string.Empty);
|
||||
}
|
||||
}
|
||||
colIndex++;
|
||||
}
|
||||
foreach (var excelParam in info.mergeParams)
|
||||
{
|
||||
MergeCells(excelParam);
|
||||
}
|
||||
int rowIndex = 4;
|
||||
foreach (var obj in info.data)
|
||||
{
|
||||
if (obj == null) continue;
|
||||
for (int i = 0; i < properties.Count; i++)
|
||||
{
|
||||
string propertieName = properties[i];
|
||||
var propertie = obj.GetType().GetProperty(propertieName);
|
||||
if (propertie is null)
|
||||
throw new ArgumentException($"Не удалось найти свойство {propertieName}");
|
||||
var value = propertie.GetValue(obj)?.ToString();
|
||||
if (value == null)
|
||||
throw new ArgumentException($"Не удалось найти свойство {propertieName}");
|
||||
InsertCellInWorksheet(new ExcelCellParameters()
|
||||
{
|
||||
Text = value,
|
||||
ColumnName = Alphabet.ElementAt(i).ToString(),
|
||||
RowIndex = (UInt32)rowIndex,
|
||||
StyleInfo = ExcelStyleInfoType.TextWithBroder,
|
||||
});
|
||||
}
|
||||
rowIndex++;
|
||||
}
|
||||
SaveExcel(info);
|
||||
}
|
||||
/// <summary>
|
||||
/// Создание excel-файла
|
||||
/// </summary>
|
||||
/// <param name="info"></param>
|
||||
protected abstract void OpenExcel<T>(ExcelInfo<T> info);
|
||||
/// <summary>
|
||||
/// Добавляем новую ячейку в лист
|
||||
/// </summary>
|
||||
/// <param name="cellParameters"></param>
|
||||
protected abstract void InsertCellInWorksheet(ExcelCellParameters
|
||||
excelParams);
|
||||
/// <summary>
|
||||
/// Объединение ячеек
|
||||
/// </summary>
|
||||
/// <param name="mergeParameters"></param>
|
||||
protected abstract void MergeCells(ExcelMergeParameters excelParams);
|
||||
/// <summary>
|
||||
/// Сохранение файла
|
||||
/// </summary>
|
||||
/// <param name="info"></param>
|
||||
protected abstract void SaveExcel<T>(ExcelInfo<T> info);
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OfficePackage.HelperEnums
|
||||
{
|
||||
public enum ExcelStyleInfoType
|
||||
{
|
||||
Title,
|
||||
Text,
|
||||
TextWithBroder
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
using OfficePackage.HelperEnums;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OfficePackage.HelperModels
|
||||
{
|
||||
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; }
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OfficePackage.HelperModels
|
||||
{
|
||||
public class ExcelInfo<T>
|
||||
{
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
public string Title { get; set; } = string.Empty;
|
||||
public string[]? Text { get; set; }
|
||||
public List<ExcelMergeParameters> mergeParams { get; set; }
|
||||
public List<int> columnWidth { get; set; }
|
||||
public List<TreeNode> tableHeadres { get; set; }
|
||||
public List<T> data { get; set; }
|
||||
|
||||
|
||||
public ExcelInfo(string fileName, string title, string[] text )
|
||||
{
|
||||
FileName = fileName;
|
||||
Title = title;
|
||||
Text = text;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OfficePackage.HelperModels
|
||||
{
|
||||
public class ExcelMergeParameters
|
||||
{
|
||||
public string CellFromName { get; set; } = string.Empty;
|
||||
public string CellToName { get; set; } = string.Empty;
|
||||
public int? ColumnFromName { get; set; } = null;
|
||||
public int? ColumnToName { get; set; } = null;
|
||||
public string Merge => $"{CellFromName}:{CellToName}";
|
||||
public string MergeColumns => $"{Alphabet.ElementAt(ColumnFromName ?? 0)}2:{Alphabet.ElementAt(ColumnToName ?? 0)}2";
|
||||
|
||||
public string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
public int colIndex { get; set; }
|
||||
public bool isHorisontel = false;
|
||||
public int count = 1;
|
||||
}
|
||||
}
|
@ -0,0 +1,393 @@
|
||||
using OfficePackage.HelperEnums;
|
||||
using OfficePackage.HelperModels;
|
||||
using DocumentFormat.OpenXml.Office2010.Excel;
|
||||
using DocumentFormat.OpenXml.Office2013.Excel;
|
||||
using DocumentFormat.OpenXml.Office2016.Excel;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using DocumentFormat.OpenXml;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Font = DocumentFormat.OpenXml.Spreadsheet.Font;
|
||||
|
||||
namespace OfficePackage.Implements
|
||||
{
|
||||
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 = false,
|
||||
Horizontal = HorizontalAlignmentValues.Left
|
||||
},
|
||||
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 OpenExcel<T>(ExcelInfo<T> 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();
|
||||
Columns columns = new Columns();
|
||||
for (int i = 0; i < info.columnWidth.Count; i++)
|
||||
{
|
||||
columns.Append(new Column() { Min = (UInt32)i + 1, Max = (UInt32)i + 1, Width = info.columnWidth[i], CustomWidth = true });
|
||||
}
|
||||
worksheetPart.Worksheet.AppendChild(columns);
|
||||
worksheetPart.Worksheet.AppendChild(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 (excelParams.ColumnName.Length != 1)
|
||||
MessageBox.Show("Буков много" + excelParams.ColumnName.Length);
|
||||
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());
|
||||
}
|
||||
}
|
||||
MergeCell mergeCell = new MergeCell();
|
||||
// foreach (var excelParam in excelParams)
|
||||
// {
|
||||
// if (excelParam.ColumnFromName == null)
|
||||
// {
|
||||
// mergeCell = new MergeCell()
|
||||
// {
|
||||
// Reference = new StringValue(excelParam.Merge)
|
||||
// };
|
||||
// mergeCells.Append(mergeCell);
|
||||
// }
|
||||
|
||||
// if (excelParam.CellFromName == string.Empty)
|
||||
// {
|
||||
// mergeCell = new MergeCell()
|
||||
// {
|
||||
// Reference = new StringValue(excelParam.MergeColumns)
|
||||
// };
|
||||
// }
|
||||
//}
|
||||
|
||||
if (excelParams.isHorisontel == false)
|
||||
{
|
||||
mergeCell = new MergeCell()
|
||||
{
|
||||
Reference = new StringValue($"{Alphabet.ElementAt(excelParams.colIndex)}2:{Alphabet.ElementAt(excelParams.colIndex)}3")
|
||||
};
|
||||
mergeCells.Append(mergeCell);
|
||||
}
|
||||
if (excelParams.isHorisontel == true)
|
||||
{
|
||||
mergeCell = new MergeCell()
|
||||
{
|
||||
Reference = new StringValue($"{Alphabet.ElementAt(excelParams.colIndex)}2:{Alphabet.ElementAt(excelParams.colIndex + excelParams.count-1)}2")
|
||||
};
|
||||
mergeCells.Append(mergeCell);
|
||||
}
|
||||
}
|
||||
protected override void SaveExcel<T>(ExcelInfo<T> info)
|
||||
{
|
||||
if (_spreadsheetDocument == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
|
||||
_spreadsheetDocument.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
46
KOP_Labs/TestProj/Form1.Designer.cs
generated
46
KOP_Labs/TestProj/Form1.Designer.cs
generated
@ -28,6 +28,7 @@
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
dropDownList1 = new Library_var_4_lab_1.DropDownList();
|
||||
textBox1 = new TextBox();
|
||||
buttonAdd = new Button();
|
||||
@ -55,6 +56,11 @@
|
||||
buttonSetItem = new Button();
|
||||
buttonGetObject = new Button();
|
||||
buttonSetIndex = new Button();
|
||||
richTextBox = new RichTextBox();
|
||||
bigTextExcel = new Library_var_4_lab_1.BigTextExcel(components);
|
||||
buttonWriteLinesToExcel = new Button();
|
||||
configurableTable1 = new Library_var_4_lab_1.ConfigurableTable(components);
|
||||
button1 = new Button();
|
||||
SuspendLayout();
|
||||
//
|
||||
// dropDownList1
|
||||
@ -171,9 +177,9 @@
|
||||
//
|
||||
// customListBox1
|
||||
//
|
||||
customListBox1.SelectedIndex = -1;
|
||||
customListBox1.Location = new Point(529, 83);
|
||||
customListBox1.Name = "customListBox1";
|
||||
customListBox1.SelectedIndex = -1;
|
||||
customListBox1.Size = new Size(463, 176);
|
||||
customListBox1.TabIndex = 12;
|
||||
//
|
||||
@ -296,11 +302,42 @@
|
||||
buttonSetIndex.UseVisualStyleBackColor = true;
|
||||
buttonSetIndex.Click += buttonSetIndex_Click;
|
||||
//
|
||||
// richTextBox
|
||||
//
|
||||
richTextBox.Location = new Point(1022, 12);
|
||||
richTextBox.Name = "richTextBox";
|
||||
richTextBox.Size = new Size(316, 229);
|
||||
richTextBox.TabIndex = 27;
|
||||
richTextBox.Text = "";
|
||||
//
|
||||
// buttonWriteLinesToExcel
|
||||
//
|
||||
buttonWriteLinesToExcel.Location = new Point(1022, 255);
|
||||
buttonWriteLinesToExcel.Name = "buttonWriteLinesToExcel";
|
||||
buttonWriteLinesToExcel.Size = new Size(316, 29);
|
||||
buttonWriteLinesToExcel.TabIndex = 28;
|
||||
buttonWriteLinesToExcel.Text = "Записать в Excel";
|
||||
buttonWriteLinesToExcel.UseVisualStyleBackColor = true;
|
||||
buttonWriteLinesToExcel.Click += buttonWriteLinesToExcel_Click;
|
||||
//
|
||||
// button1
|
||||
//
|
||||
button1.Location = new Point(1115, 320);
|
||||
button1.Name = "button1";
|
||||
button1.Size = new Size(94, 29);
|
||||
button1.TabIndex = 29;
|
||||
button1.Text = "button1";
|
||||
button1.UseVisualStyleBackColor = true;
|
||||
button1.Click += buttonConfigTable_Click;
|
||||
//
|
||||
// Form1
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(1007, 549);
|
||||
ClientSize = new Size(1350, 549);
|
||||
Controls.Add(button1);
|
||||
Controls.Add(buttonWriteLinesToExcel);
|
||||
Controls.Add(richTextBox);
|
||||
Controls.Add(buttonSetIndex);
|
||||
Controls.Add(buttonGetObject);
|
||||
Controls.Add(buttonSetItem);
|
||||
@ -363,5 +400,10 @@
|
||||
private Button buttonSetItem;
|
||||
private Button buttonGetObject;
|
||||
private Button buttonSetIndex;
|
||||
private RichTextBox richTextBox;
|
||||
private Library_var_4_lab_1.BigTextExcel bigTextExcel;
|
||||
private Button buttonWriteLinesToExcel;
|
||||
private Library_var_4_lab_1.ConfigurableTable configurableTable1;
|
||||
private Button button1;
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using Library_var_4_lab_1;
|
||||
using OfficePackage.HelperModels;
|
||||
|
||||
namespace TestProj
|
||||
{
|
||||
@ -95,5 +96,58 @@ namespace TestProj
|
||||
{
|
||||
textBoxInput.Text = customListBox1.SelectedIndex.ToString();
|
||||
}
|
||||
|
||||
// ëàáà 2
|
||||
// òàñêà 1
|
||||
|
||||
private void buttonWriteLinesToExcel_Click(object sender, EventArgs e)
|
||||
{
|
||||
bigTextExcel.WriteToExcel("C:\\Users\\123\\Desktop\\Lab2_KOP1.xlsx", "Çàãîëîâîê", richTextBox.Lines);
|
||||
}
|
||||
|
||||
//òàñêà 2
|
||||
|
||||
private void buttonConfigTable_Click(object sender, EventArgs e)
|
||||
{
|
||||
List<ExcelMergeParameters> mergeParameters = new();
|
||||
mergeParameters.Add(new ExcelMergeParameters()
|
||||
{
|
||||
colIndex = 0,
|
||||
isHorisontel = false
|
||||
});
|
||||
mergeParameters.Add(new ExcelMergeParameters()
|
||||
{
|
||||
colIndex = 1,
|
||||
isHorisontel = true,
|
||||
count = 2
|
||||
});
|
||||
List<int> width = new();
|
||||
width.Add(20);
|
||||
width.Add(20);
|
||||
width.Add(50);
|
||||
List<TreeNode> headers = new List<TreeNode>();
|
||||
headers.Add(new TreeNode()
|
||||
{
|
||||
Text = "Ãðóïïà",
|
||||
Tag = "Group"
|
||||
});
|
||||
TreeNode node1 = new();
|
||||
node1.Text = "Èìÿ";
|
||||
node1.Tag = "Name";
|
||||
TreeNode node2 = new();
|
||||
node2.Text = "Ôàìèëèÿ";
|
||||
node2.Tag = "SurName";
|
||||
TreeNode node3 = new();
|
||||
node3.Text = "ÔÈÎ";
|
||||
node3.Nodes.Add(node1);
|
||||
node3.Nodes.Add(node2);
|
||||
headers.Add(node3);
|
||||
List<Human> people = new List<Human>();
|
||||
people.Add(new Human() { Group = "ÏÈáä-33", Name = "Àðò¸ì", SurName = "ßøèí" });
|
||||
people.Add(new Human() { Group = "ÏÈáä-33", Name = "Ðîñòèñëàâ", SurName = "Çàõàðîâ" });
|
||||
people.Add(new Human() { Group = "ÏÈáä-33", Name = "Íèÿç", SurName = "Þíóñîâ" });
|
||||
configurableTable1.CreateTable<Human>("C:\\Users\\123\\Desktop\\Lab2_KOP1.xlsx", "Çàãîëîâîê", mergeParameters, width, headers, people);
|
||||
MessageBox.Show("Ãîòîâî ¸áàíà");
|
||||
}
|
||||
}
|
||||
}
|
@ -117,4 +117,10 @@
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="bigTextExcel.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="configurableTable1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>156, 17</value>
|
||||
</metadata>
|
||||
</root>
|
@ -11,5 +11,6 @@ namespace TestProj
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string SurName { get; set; } = string.Empty;
|
||||
public int Age { get; set; }
|
||||
public string Group { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user