ИСЭбд-21 Мосевнин А.М. LabWork_3 #3

Closed
Aleks_andr435 wants to merge 3 commits from Labwork_3 into LabWork_2
10 changed files with 804 additions and 15 deletions
Showing only changes of commit d858e02844 - Show all commits

View File

@ -37,6 +37,7 @@
обновлениеБилетаToolStripMenuItem = new ToolStripMenuItem();
заказатьКнигиToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
DocReportToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
@ -47,8 +48,8 @@
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетыToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(5, 2, 0, 2);
menuStrip1.Size = new Size(728, 24);
menuStrip1.Padding = new Padding(6, 3, 0, 3);
menuStrip1.Size = new Size(832, 30);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip";
//
@ -56,27 +57,27 @@
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { книгаToolStripMenuItem, читателиToolStripMenuItem, библиотекиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники";
//
// книгаToolStripMenuItem
//
книгаToolStripMenuItem.Name = "книгаToolStripMenuItem";
книгаToolStripMenuItem.Size = new Size(180, 22);
книгаToolStripMenuItem.Size = new Size(175, 26);
книгаToolStripMenuItem.Text = "Книга";
книгаToolStripMenuItem.Click += книгаToolStripMenuItem_Click;
//
// читателиToolStripMenuItem
//
читателиToolStripMenuItem.Name = "читателиToolStripMenuItem";
читателиToolStripMenuItem.Size = new Size(180, 22);
читателиToolStripMenuItem.Size = new Size(175, 26);
читателиToolStripMenuItem.Text = "Читатели";
читателиToolStripMenuItem.Click += читателиToolStripMenuItem_Click;
//
// библиотекиToolStripMenuItem
//
библиотекиToolStripMenuItem.Name = "библиотекиToolStripMenuItem";
библиотекиToolStripMenuItem.Size = new Size(180, 22);
библиотекиToolStripMenuItem.Size = new Size(175, 26);
библиотекиToolStripMenuItem.Text = "Библиотеки";
библиотекиToolStripMenuItem.Click += библиотекиToolStripMenuItem_Click;
//
@ -84,39 +85,46 @@
//
операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { обновлениеБилетаToolStripMenuItem, заказатьКнигиToolStripMenuItem });
операцииToolStripMenuItem.Name = "операцииToolStripMenuItem";
операцииToolStripMenuItem.Size = new Size(75, 20);
операцииToolStripMenuItem.Size = new Size(95, 24);
операцииToolStripMenuItem.Text = "Операции";
//
// обновлениеБилетаToolStripMenuItem
//
обновлениеБилетаToolStripMenuItem.Name = "обновлениеБилетаToolStripMenuItem";
обновлениеБилетаToolStripMenuItem.Size = new Size(184, 22);
обновлениеБилетаToolStripMenuItem.Size = new Size(232, 26);
обновлениеБилетаToolStripMenuItem.Text = "Обновление билета";
обновлениеБилетаToolStripMenuItem.Click += обновлениеБилетаToolStripMenuItem_Click;
//
// заказатьКнигиToolStripMenuItem
//
заказатьКнигиToolStripMenuItem.Name = аказатьКнигиToolStripMenuItem";
заказатьКнигиToolStripMenuItem.Size = new Size(184, 22);
заказатьКнигиToolStripMenuItem.Size = new Size(232, 26);
заказатьКнигиToolStripMenuItem.Text = "Заказать книги";
заказатьКнигиToolStripMenuItem.Click += заказатьКнигиToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DocReportToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(60, 20);
отчетыToolStripMenuItem.Size = new Size(73, 24);
отчетыToolStripMenuItem.Text = "Отчеты";
//
// DocReportToolStripMenuItem
//
DocReportToolStripMenuItem.Name = "DocReportToolStripMenuItem";
DocReportToolStripMenuItem.Size = new Size(294, 26);
DocReportToolStripMenuItem.Text = "Документ со справочниками";
DocReportToolStripMenuItem.Click += DocReportToolStripMenuItem_Click;
//
// FormLibrary
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = SystemColors.ButtonHighlight;
BackgroundImage = Properties.Resources.Снимок_экрана_2024_11_19_132940;
ClientSize = new Size(728, 340);
ClientSize = new Size(832, 453);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Margin = new Padding(3, 2, 3, 2);
Name = "FormLibrary";
StartPosition = FormStartPosition.CenterScreen;
Text = "Библиотека";
@ -137,5 +145,6 @@
private ToolStripMenuItem читателиToolStripMenuItem;
private ToolStripMenuItem библиотекиToolStripMenuItem;
private ToolStripMenuItem заказатьКнигиToolStripMenuItem;
private ToolStripMenuItem DocReportToolStripMenuItem;
}
}

View File

@ -71,5 +71,17 @@ namespace ProjectLibrary
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DocReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<Forms.FormDocReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Microsoft ResX Schema
Version 2.0
@ -48,7 +48,7 @@
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

View File

@ -0,0 +1,100 @@
namespace ProjectLibrary.Forms
{
partial class FormDocReport
{
/// <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()
{
checkBoxBooks = new CheckBox();
checkBoxReaders = new CheckBox();
checkBoxIncludeTicketExtensions = new CheckBox();
buttonCreate = new Button();
SuspendLayout();
//
// checkBoxBooks
//
checkBoxBooks.AutoSize = true;
checkBoxBooks.Location = new Point(54, 34);
checkBoxBooks.Name = "checkBoxBooks";
checkBoxBooks.Size = new Size(73, 24);
checkBoxBooks.TabIndex = 0;
checkBoxBooks.Text = "Книги";
checkBoxBooks.UseVisualStyleBackColor = true;
//
// checkBoxReaders
//
checkBoxReaders.AutoSize = true;
checkBoxReaders.Location = new Point(54, 101);
checkBoxReaders.Name = "checkBoxReaders";
checkBoxReaders.Size = new Size(95, 24);
checkBoxReaders.TabIndex = 1;
checkBoxReaders.Text = "Читатели";
checkBoxReaders.UseVisualStyleBackColor = true;
//
// checkBoxIncludeTicketExtensions
//
checkBoxIncludeTicketExtensions.AutoSize = true;
checkBoxIncludeTicketExtensions.Location = new Point(54, 170);
checkBoxIncludeTicketExtensions.Name = "checkBoxIncludeTicketExtensions";
checkBoxIncludeTicketExtensions.Size = new Size(114, 24);
checkBoxIncludeTicketExtensions.TabIndex = 2;
checkBoxIncludeTicketExtensions.Text = "Библиотеки";
checkBoxIncludeTicketExtensions.UseVisualStyleBackColor = true;
//
// buttonCreate
//
buttonCreate.BackColor = SystemColors.Control;
buttonCreate.Location = new Point(278, 101);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(133, 29);
buttonCreate.TabIndex = 3;
buttonCreate.Text = "Сформировать";
buttonCreate.UseVisualStyleBackColor = false;
buttonCreate.Click += ButtonCreate_Click;
//
// FormDocReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(484, 236);
Controls.Add(buttonCreate);
Controls.Add(checkBoxIncludeTicketExtensions);
Controls.Add(checkBoxReaders);
Controls.Add(checkBoxBooks);
Name = "FormDocReport";
Text = "Выгрузка справочников";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxBooks;
private CheckBox checkBoxReaders;
private CheckBox checkBoxIncludeTicketExtensions;
private Button buttonCreate;
}
}

View File

@ -0,0 +1,58 @@
using ProjectLibrary.Reports;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectLibrary.Forms;
public partial class FormDocReport : Form
{
private readonly IUnityContainer _container;
public FormDocReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxBooks.Checked && !checkBoxReaders.Checked && !checkBoxIncludeTicketExtensions.Checked)
{
throw new Exception("Не выбран ни один справочник для выгрузки");
}
var sfd = new SaveFileDialog()
{
Filter = "Docx Files | *.docx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
throw new Exception("Не выбран файла для отчета");
}
if (_container.Resolve<DocReport>().CreateDoc(sfd.FileName, checkBoxBooks.Checked,
checkBoxReaders.Checked, checkBoxIncludeTicketExtensions.Checked))
{
MessageBox.Show("Документ сформирован", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@ -0,0 +1,120 @@
<?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>
</root>

View File

@ -10,6 +10,7 @@
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />

View File

@ -0,0 +1,88 @@
using Microsoft.Extensions.Logging;
using ProjectLibrary.Repositores;
using ProjectLibrary.Repositories;
using ProjectLibrary.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLibrary.Reports;
public class DocReport
{
private readonly IBookRepository _bookRepository;
private readonly IReaderRepository _readerRepository;
private readonly ITicketExtensionsRepository _ticketExtensionsRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IBookRepository bookRepository, IReaderRepository readerRepository,
ITicketExtensionsRepository ticketExtensionsRepository, ILogger<DocReport> logger)
{
_bookRepository = bookRepository ?? throw new ArgumentNullException(nameof(bookRepository));
_readerRepository = readerRepository ?? throw new ArgumentNullException(nameof(readerRepository));
_ticketExtensionsRepository = ticketExtensionsRepository ?? throw new ArgumentNullException(nameof(ticketExtensionsRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeBooks, bool includeReaders, bool includeTicketExtensions)
{
try
{
var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками");
if (includeBooks)
{
builder.AddParagraph("Книги").AddTable([2400, 2400, 1200], GetBooks());
}
if (includeReaders)
{
builder.AddParagraph("Читатели").AddTable([2400, 1200, 1200], GetReaders());
}
if (includeTicketExtensions)
{
builder.AddParagraph("Библиотеки").AddTable([2400, 2400, 2400], GetTicketExtensions());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetBooks()
{
return [
["Автор", "Название", "Тип книги"],
.. _bookRepository
.ReadBooks()
.Select(x => new string[] { x.Author, x.Name, x.TypeBookID.ToString()}),
];
}
private List<string[]> GetReaders()
{
return [
["ФИО читателя", "Билет читателя", "Дата регистрации"],
.. _readerRepository
.ReadReaders()
.Select(x => new string[] { x.Name, x.ReaderTicket.ToString(), x.RegistrationDateRT.ToString()}),
];
}
private List<string[]> GetTicketExtensions()
{
return [
["ID Читателя", "Последняя дата обновления", "Следующая дата обновления"],
.. _ticketExtensionsRepository
.ReadTicketExtensions()
.Select(x => new string[] {x.ReaderID.ToString(), x.LastUpdateDate.ToString(), x.NextUpdateDate.ToString()}),
];
}
}

View File

@ -0,0 +1,308 @@
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;
namespace ProjectLibrary.Reports;
public class ExcelBuilder
{
private readonly string _filePath;
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public ExcelBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public ExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public ExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
return this;
}
public ExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public void Build()
{
using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
}
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts()
{
Count = 2,
KnownFonts = BooleanValue.FromBoolean(true)
};
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
Bold = new Bold(),
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill()
{
PatternType = new EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Medium },
RightBorder = new RightBorder() { Style = BorderStyleValues.Medium },
TopBorder = new TopBorder() { Style = BorderStyleValues.Medium },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Medium },
DiagonalBorder = new DiagonalBorder() { Style = BorderStyleValues.Medium },
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 1,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 2,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 3,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 2,
BoldTextWithBorder = 3
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>().FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() +
columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}

View File

@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace ProjectLibrary.Reports;
public class WordBuilder
{
private readonly string _filePath;
private readonly Document _document;
private readonly Body _body;
public WordBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
_body = _document.AppendChild(new Body());
}
public WordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.PrependChild(new RunProperties());
run.RunProperties.AddChild(new Bold());
run.AppendChild(new Text(header));
return this;
}
public WordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public WordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 })));
// Заголовок
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
}
table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x => new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public void Build()
{
using var wordDocument = WordprocessingDocument.Create(_filePath,
WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
}
}