начало работы с отчетами word, excel

This commit is contained in:
EkaterinaR 2024-11-06 03:05:29 +04:00
parent 3d709d3b57
commit 60740d3ca9
24 changed files with 1034 additions and 292 deletions

View File

@ -11,6 +11,8 @@ using System.Numerics;
using System.Security.Cryptography.Xml;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
using static System.Runtime.InteropServices.JavaScript.JSType;
using DocumentFormat.OpenXml.Office2010.Excel;
namespace EventVisitorClientApp.Controllers
{
@ -238,7 +240,13 @@ namespace EventVisitorClientApp.Controllers
Link = eventDetails.Link,
FreePlaces = updatedFreePlaces
});
Response.Redirect("ResultRegistration");
APIClient.PostRequest("api/main/SendToMail", new MailSendInfoBindingModel
{
MailAddress = email,
Subject = "Ðåãèñòðàöèÿ íà ìåðîïðèÿòèå",
Text = "Âû çàðåãåñòðèðîâàíû íà ìåðîïðèÿòèå " + eventDetails.Name + ", êîòîðîå ïðîéäåò " + eventDetails.TimeStart + ". Ïî àäðåñó: " + eventDetails.Address + " ã. " + eventDetails.City + ".\n" + "Ïî âñåì âîïðîñàì ìîæíî îáðàùàòüñÿ ïî òåëåôîíó: " + eventDetails.ContactPhone + " èëè ïî ïî÷òå: " + eventDetails.ContactEmail + ".\n" + "Áóäåì æäàòü Âàñ íà íàøèõ ìåðîïðèÿòèÿõ!"
});
Response.Redirect("ResultRegistration");
}
else
{
@ -304,6 +312,17 @@ namespace EventVisitorClientApp.Controllers
return View(eventDetails);
}
public IActionResult SendMessage(int id)
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
var eventDetails = APIClient.GetRequest<EventViewModel>($"api/main/GetEvent?EventId={id}");
return View(eventDetails);
}
[HttpPost]
public void UpdateEvent(int id, string name, string description, string type, string phone, string email, string address, string city, string status, int count, DateTime timestart, DateTime timeend)
@ -331,5 +350,39 @@ namespace EventVisitorClientApp.Controllers
});
Response.Redirect("MyEvents");
}
public IActionResult GetWordFile()
{
return new PhysicalFileResult("F:\\EventVisitor\\wordfile.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
}
public IActionResult GetExcelFile()
{
return new PhysicalFileResult("F:\\EventVisitor\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
//[HttpPost]
//public void ReportWord(int[] Ids, int id)
//{
// if (APIClient.Client == null)
// {
// throw new Exception("Âû êàê ñóäà ïîïàëè? Ñóäà âõîä òîëüêî àâòîðèçîâàííûì");
// }
// List<VisitorViewModel> registeredVisitorsIds = APIClient.GetRequest<List<VisitorViewModel>>($"api/main/GetVisitorList?EventId={id}");
// foreach (var item in Ids)
// {
// res.Add(item);
// }
// APIClient.PostRequest("api/main/createreporttowordfile", new ReportVisitorsBindingModel
// {
// Ids = res,
// FileName = "F:\\EventVisitor\\wordfile.docx"
// });
// Response.Redirect("GetWordFile");
//}
}
}

View File

@ -1,5 +1,7 @@
using EventVisitorClientApp;
using EventVisitorDatabase.Implements;
using EventVisitorLogic.OfficePackage.Implements;
using EventVisitorLogic.OfficePackage;
using EventVisitorLogic.StoragesContracts;
var builder = WebApplication.CreateBuilder(args);
@ -9,6 +11,8 @@ builder.Services.AddControllersWithViews();
builder.Services.AddTransient<IEventStorage, EventStorage>();
builder.Services.AddTransient<IVisitorStorage, VisitorStorage>();
builder.Services.AddTransient<IOrganizerStorage, OrganizerStorage>();
builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
var app = builder.Build();
APIClient.Connect(builder.Configuration);

View File

@ -0,0 +1,77 @@
@using EventVisitorLogic.ViewModels
@model List<EventViewModel>
@{
ViewData["Title"] = "ReportWordExel";
}
<div class="text-center">
<h2>
Создание отчета word/exel
</h2>
</div>
<div class="text-center">
<form method="post">
<div>
<label>
Выберите формат файла:
</label>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="type" value="docx" id="docx">
<label for="docx">
Word-файл
</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="type" value="xlsx" id="xlsx" checked>
<label for="xlsx">
Excel-файл
</label>
</div>
</div>
<div>
<div>
<div>
<table class="table">
<thead>
<tr>
<th>
</th>
<th>
Имя
</th>
<th>
Телефон
</th>
<th>
Почта
</th>
<th>
Статус
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" class="form-check-input" name="Ids[]" value="@item.Id" id="@item.Id">
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
<div class="u-align-center u-form-group u-form-submit u-label-top" style="padding-bottom: 120px">
<div class="col-8"></div>
<div class="col-4"><input type="submit" class="btn btn-success" value="Создать файл"></div>
</div>
</form>
</div>

View File

@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace EventVisitorClientApp.Views.Home
{
public class ReportWordExelModel : PageModel
{
public void OnGet()
{
}
}
}

View File

@ -52,7 +52,9 @@
</div>
</div>
<a class="btn btn-dark btn-block mb-4" asp-action="RegistrationOnEvent" asp-route-id="@Model.Id">Страница с регистрацией</a>
<a class="btn btn-dark btn-block mb-4" asp-action="Visitors" asp-route-id="@Model.Id">Зарегистрированные пользователи</a>
<a class="btn btn-dark btn-block mb-4" asp-action="Visitors" asp-route-id="@Model.Id">Посетители</a>
<a class="btn btn-dark btn-block mb-4" asp-action="ReportWord" asp-route-id="@Model.Id">Отчет Word о посетителях </a>
<a class="btn btn-dark btn-block mb-4" asp-action="ReportExcel" asp-route-id="@Model.Id">Отчет Excel о посетителях </a>
</div>
</div>
</div>

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.BindingModels
{
public class ReportVisitorsBindingModel
{
public string FileName { get; set; } = string.Empty;
public int EventId { get; set; }
public List<int>? Ids { get; set; }
}
}

View File

@ -6,6 +6,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EventVisitorModels\EventVisitorModels.csproj" />
</ItemGroup>

View File

@ -0,0 +1,17 @@
using EventVisitorLogic.BindingModels;
using EventVisitorLogic.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.Logic
{
public interface IReportLogic
{
List<ReportVisitorsViewModel> GetVisitors(ReportVisitorsBindingModel model);
void SaveVisitorsToWordFile(ReportVisitorsBindingModel model);
void SaveVisitorsToExcelFile(ReportVisitorsBindingModel model);
}
}

View File

@ -0,0 +1,69 @@
using EventVisitorLogic.OfficePackage.HelperModels;
using EventVisitorLogic.OfficePackage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EventVisitorLogic.StoragesContracts;
using EventVisitorLogic.ViewModels;
using EventVisitorLogic.BindingModels;
namespace EventVisitorLogic.Logic
{
public class ReportLogic : IReportLogic
{
private readonly IVisitorStorage _visitorStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
public ReportLogic(IVisitorStorage visitorStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord)
{
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_visitorStorage = visitorStorage;
}
public List<ReportVisitorsViewModel> GetVisitors(ReportVisitorsBindingModel model)
{
var listAll = new List<ReportVisitorsViewModel>();
var listVisitors = _visitorStorage.GetFilteredList(new VisitorBindingModel
{
EventId = model.EventId
});
foreach (var recipe in listVisitors)
{
listAll.Add(new ReportVisitorsViewModel
{
Name = recipe.Name,
Email = recipe.Email,
Phone = recipe.Phone,
Status = recipe.Status
});
}
return listAll;
}
public void SaveVisitorsToExcelFile(ReportVisitorsBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список посетителей мероприятия",
Visitors = GetVisitors(model)
});
}
public void SaveVisitorsToWordFile(ReportVisitorsBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список посетителей мероприятия",
Visitors = GetVisitors(model)
});
}
}
}

View File

@ -0,0 +1,65 @@
using EventVisitorLogic.OfficePackage.HelperEnums;
using EventVisitorLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public void CreateReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
uint rowIndex = 2;
foreach (var pc in info.Visitors)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.Name,
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = pc.Email,
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = pc.Phone,
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "D",
RowIndex = rowIndex,
Text = pc.Status,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
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

@ -0,0 +1,45 @@
using EventVisitorLogic.OfficePackage.HelperEnums;
using EventVisitorLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateDoc(WordInfo info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var km in info.Visitors)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{ (km.Name, new WordTextProperties { Size = "20", Bold=true}), (km.Email, new WordTextProperties { Size = "20", Bold=true}), (km.Phone, new WordTextProperties { Size = "20", Bold=true}), (km.Status, new WordTextProperties { Size = "20", Bold=true})},
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfo info);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage.HelperEnums
{
public enum ExcelStyleInfoType
{
Title,
Text,
TextWithBroder
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage.HelperEnums
{
public enum WordJustificationType
{
Center,
Both
}
}

View File

@ -0,0 +1,18 @@
using EventVisitorLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.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; }
}
}

View File

@ -0,0 +1,20 @@
using EventVisitorLogic.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage.HelperModels
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportVisitorsViewModel> Visitors
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage.HelperModels
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -0,0 +1,16 @@
using EventVisitorLogic.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportVisitorsViewModel> Visitors { get; set; } = new();
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; } = new();
public WordTextProperties? TextProperties { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using EventVisitorLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; } = string.Empty;
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,355 @@
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using EventVisitorLogic.OfficePackage.HelperEnums;
using EventVisitorLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.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 = 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.Close();
}
}
}

View File

@ -0,0 +1,121 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using EventVisitorLogic.OfficePackage.HelperEnums;
using EventVisitorLogic.OfficePackage.HelperModels;
namespace EventVisitorLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
private static JustificationValues
GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
/// <summary>
/// Настройки страницы
/// </summary>
/// <returns></returns>
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
/// <summary>
/// Задание форматирования для абзаца
/// </summary>
/// <param name="paragraphProperties"></param>
/// <returns></returns>
private static ParagraphProperties?
CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val =
GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize
{
Val =
paragraphProperties.Size
});
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
protected override void CreateWord(WordInfo info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName,
WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text
{
Text = run.Item1,
Space =
SpaceProcessingModeValues.Preserve
});
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EventVisitorLogic.ViewModels
{
public class ReportVisitorsViewModel
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Phone { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
}
}

View File

@ -12,12 +12,16 @@ namespace EventVisitorRestApi.Controllers
private readonly IOrganizerLogic _organizer;
private readonly IEventLogic _event;
private readonly IVisitorLogic _visitor;
private readonly IReportLogic _reportLogic;
private readonly AbstractMailWorker _mailWorker;
public MainController(IOrganizerLogic organizer, IEventLogic events, IVisitorLogic visitor)
public MainController(IOrganizerLogic organizer, IEventLogic events, IVisitorLogic visitor, AbstractMailWorker mailWorker, IReportLogic reportLogic)
{
_organizer = organizer;
_event = events;
_visitor = visitor;
_mailWorker = mailWorker;
_reportLogic = reportLogic;
}
/// Мероприятия
[HttpGet]
@ -86,127 +90,6 @@ namespace EventVisitorRestApi.Controllers
}
}
//[HttpGet]
//public List<ProceduresViewModel>? GetProcedures()
//{
// try
// {
// return _procedure.ReadList(null);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка получения списка процедур");
// throw;
// }
//}
//[HttpPost]
//public void CreateProcedure(ProceduresBindingModel model)
//{
// try
// {
// _procedure.Create(model);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка создания процедуры");
// throw;
// }
//}
//[HttpPost]
//public void UpdateProcedure(ProceduresBindingModel model)
//{
// try
// {
// model.ProcedureMedicine = null!;
// _procedure.Update(model);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка обновления процедуры");
// throw;
// }
//}
//[HttpGet]
//public Tuple<ProceduresViewModel, List<Tuple<string>>>? GetProcedure(int procedureId)
//{
// try
// {
// var elem = _procedure.ReadElement(new ProceduresSearchModel { Id = procedureId });
// if (elem == null)
// return null;
// return Tuple.Create(elem, elem.ProcedureMedicine.Select(x => Tuple.Create(x.Value.MedicinesName)).ToList());
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка получения процедуры по id={Id}", procedureId);
// throw;
// }
//}
////private ProceduresBindingModel GetModelWithMedicines(ProceduresBindingModel model)
////{
//// var medicines = _medicine.ReadList(new MedicinesSearchModel { Ids = model.ProcedureMedicine.Keys.ToArray() });
//// if (medicines != null)
//// {
//// model.ProcedureMedicine = medicines.Where(m => model.ProcedureMedicine.Keys.Contains(m.Id))
//// .ToDictionary(m => m.Id, m => m as IMedicinesModel);
//// }
//// return model;
////}
//[HttpPost]
//public void DeleteProcedure(ProceduresBindingModel model)
//{
// try
// {
// _procedure.Delete(model);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка удаления процедуры");
// throw;
// }
//}
///// <summary>
///// ЛЕКАРСТВА
///// </summary>
///// <returns></returns>
//[HttpGet]
//public List<MedicinesViewModel>? GetMedicinesList(int? clientId)
//{
// try
// {
// if (clientId == null)
// {
// return _medicine.ReadList(null);
// }
// return _medicine.ReadList(new MedicinesSearchModel
// {
// ClientId = clientId
// });
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка получения списка лекарств");
// throw;
// }
//}
//[HttpGet]
//public List<MedicinesViewModel>? GetMedicines()
//{
// try
// {
// return _medicine.ReadList(null);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка получения списка лекарств");
// throw;
// }
//}
[HttpGet]
public EventViewModel? GetEvent(int eventId)
{
@ -223,19 +106,7 @@ namespace EventVisitorRestApi.Controllers
}
}
//[HttpPost]
//public void CreateMedicine(MedicinesBindingModel model)
//{
// try
// {
// _medicine.Create(model);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка создания лекарства");
// throw;
// }
//}
[HttpPost]
public void UpdateEvent(EventBindingModel model)
{
@ -262,163 +133,44 @@ namespace EventVisitorRestApi.Controllers
}
}
///// <summary>
///// РЕЦЕПТЫ
///// </summary>
///// <returns></returns>
[HttpPost]
public void SendToMail(MailSendInfoBindingModel model)
{
try
{
_mailWorker.MailSendAsync(model);
}
catch (Exception ex)
{
throw;
}
}
//[HttpGet]
//public List<RecipesViewModel>? GetRecipesList(int clientId)
//{
// try
// {
// return _recipe.ReadList(new RecipesSearchModel
// {
// ClientId = clientId,
// });
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка получения списка рецептов");
// throw;
// }
//}
//[HttpPost]
//public void CreateRecipe(RecipesBindingModel model)
//{
// try
// {
// _recipe.Create(model);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка создания рецепта");
// throw;
// }
//}
[HttpPost]
public void CreateReportToWordFile(ReportVisitorsBindingModel model)
{
try
{
_reportLogic.SaveVisitorsToWordFile(model);
}
catch (Exception ex)
{
throw;
}
}
//[HttpGet]
//public List<RecipesViewModel>? GetRecipes()
//{
// try
// {
// return _recipe.ReadList(null);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка получения списка рецептов");
// throw;
// }
//}
////[HttpGet]
////public RecipesViewModel? GetRecipe(int recipeId)
////{
//// try
//// {
//// return _recipe.ReadElement(new RecipesSearchModel
//// {
//// Id = recipeId
//// });
//// }
//// catch (Exception ex)
//// {
//// _logger.LogError(ex, "Ошибка получения рецепта по id={Id}", recipeId);
//// throw;
//// }
////}
[HttpPost]
public void CreateReportToExcelFile(ReportVisitorsBindingModel model)
{
try
{
_reportLogic.SaveVisitorsToExcelFile(model);
}
catch (Exception ex)
{
throw;
}
}
//[HttpPost]
//public void UpdateRecipe(RecipesBindingModel model)
//{
// try
// {
// model.RecipeProcedures = null!;
// _recipe.Update(model);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка обновления данных");
// throw;
// }
//}
//[HttpGet]
//public Tuple<RecipesViewModel, List<Tuple<string>>>? GetRecipe(int recipeId)
//{
// try
// {
// var elem = _recipe.ReadElement(new RecipesSearchModel { Id = recipeId });
// if (elem == null)
// return null;
// return Tuple.Create(elem, elem.RecipeProcedures.Select(x => Tuple.Create(x.Value.ProceduresName)).ToList());
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка получения процедуры по id={Id}", recipeId);
// throw;
// }
//}
//[HttpPost]
//public void AddProcedures(Tuple<RecipesSearchModel, ProceduresViewModel> model)
//{
// try
// {
// _recipe.AddProcedures(model.Item1, model.Item2);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка добавления процедуры в рецепт.");
// throw;
// }
//}
//[HttpPost]
//public void AddMedicineToProcedure(Tuple<ProceduresSearchModel, MedicinesViewModel> model)
//{
// try
// {
// _procedure.AddMedicineToProcedure(model.Item1, model.Item2);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка добавления лекарства в процедуру.");
// throw;
// }
//}
//private RecipesBindingModel GetModelWithProcedures(RecipesBindingModel model)
//{
// var medicines = _procedure.ReadList(new ProceduresSearchModel { Ids = model.RecipeProcedures.Keys.ToArray() });
// if (medicines != null)
// {
// model.RecipeProcedures = medicines.Where(m => model.RecipeProcedures.Keys.Contains(m.Id))
// .ToDictionary(m => m.Id, m => m as IProceduresModel);
// }
// return model;
//}
//[HttpPost]
//public void DeleteRecipe(RecipesBindingModel model)
//{
// try
// {
// _recipe.Delete(model);
// }
// catch (Exception ex)
// {
// _logger.LogError(ex, "Ошибка удаления рецепта");
// throw;
// }
//}
//[HttpGet]
//public List<SymptomsViewModel>? GetSymptoms()
//{
// try
// {
// return _symptom.ReadList(null);
// }
// catch (Exception ex)
// {
// throw;
// }
//}
}
}

View File

@ -2,6 +2,8 @@ using EventVisitorDatabase;
using EventVisitorDatabase.Implements;
using EventVisitorLogic.BindingModels;
using EventVisitorLogic.Logic;
using EventVisitorLogic.OfficePackage.Implements;
using EventVisitorLogic.OfficePackage;
using EventVisitorLogic.StoragesContracts;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
@ -29,6 +31,11 @@ builder.Services.AddTransient<IEventLogic, EventLogic>();
builder.Services.AddTransient<IOrganizerLogic, OrganizerLogic>();
builder.Services.AddTransient<IVisitorLogic, VisitorLogic>();
builder.Services.AddTransient<IReportLogic, ReportLogic>();
builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
var app = builder.Build();