отчетам быть!!!

This commit is contained in:
EkaterinaR 2024-12-02 02:20:47 +04:00
parent d2d0f04421
commit d45eab6e3b
9 changed files with 124 additions and 49 deletions

View File

@ -5,22 +5,6 @@ using EventVisitorLogic.ViewModels;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Net;
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;
using System.Text;
using System.Security.Cryptography;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
namespace EventVisitorClientApp.Controllers namespace EventVisitorClientApp.Controllers
{ {
@ -639,24 +623,24 @@ namespace EventVisitorClientApp.Controllers
/// Îò÷åòû /// Îò÷åòû
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public IActionResult GetWordFile() ///
[HttpPost]
public IActionResult ReportExcel(int id)
{ {
var filePath = "F:\\EventVisitor\\wordfile.docx"; if (APIClient.Client == null)
if (!System.IO.File.Exists(filePath))
{ {
return NotFound(); throw new Exception("Âû êàê ñóäà ïîïàëè? Ñóäà âõîä òîëüêî àâòîðèçîâàííûì");
} }
var reportFilePath = $"F:\\EventVisitor\\Report_{id}_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xlsx";
return new PhysicalFileResult(filePath, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); APIClient.PostRequest("api/main/createreporttoexcelfile", new ReportVisitorsBindingModel
}
public IActionResult GetExcelFile()
{ {
return new PhysicalFileResult("F:\\EventVisitor\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); EventId = id,
} FileName = reportFilePath
});
return PhysicalFile(reportFilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
$"Report_{id}.xlsx");
}
[HttpPost] [HttpPost]
public IActionResult ReportWord(int id) public IActionResult ReportWord(int id)
@ -666,15 +650,20 @@ namespace EventVisitorClientApp.Controllers
throw new Exception("Âû êàê ñóäà ïîïàëè? Ñóäà âõîä òîëüêî àâòîðèçîâàííûì"); throw new Exception("Âû êàê ñóäà ïîïàëè? Ñóäà âõîä òîëüêî àâòîðèçîâàííûì");
} }
// Ñîçäàéòå îò÷åò
var reportFilePath = $"F:\\EventVisitor\\Report_{id}_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.docx";
APIClient.PostRequest("api/main/createreporttowordfile", new ReportVisitorsBindingModel APIClient.PostRequest("api/main/createreporttowordfile", new ReportVisitorsBindingModel
{ {
EventId = id, EventId = id,
FileName = "F:\\EventVisitor\\wordfile.docx" FileName = reportFilePath
}); });
return RedirectToAction("GetWordFile");
// Âîçâðàùàåì ôàéë è óñòàíàâëèâàåì èìÿ ôàéëà äëÿ ñîõðàíåíèÿ
return PhysicalFile(reportFilePath, "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
$"Report_{id}.docx");
} }
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error(string errorMessage, string returnUrl) public IActionResult Error(string errorMessage, string returnUrl)
{ {

View File

@ -3,11 +3,13 @@ using EventVisitorDatabase.Implements;
using EventVisitorLogic.OfficePackage.Implements; using EventVisitorLogic.OfficePackage.Implements;
using EventVisitorLogic.OfficePackage; using EventVisitorLogic.OfficePackage;
using EventVisitorLogic.StoragesContracts; using EventVisitorLogic.StoragesContracts;
using EventVisitorLogic.Logic;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
builder.Services.AddControllersWithViews(); builder.Services.AddControllersWithViews();
builder.Services.AddTransient<IReportLogic, ReportLogic>();
builder.Services.AddTransient<IEventStorage, EventStorage>(); builder.Services.AddTransient<IEventStorage, EventStorage>();
builder.Services.AddTransient<IVisitorStorage, VisitorStorage>(); builder.Services.AddTransient<IVisitorStorage, VisitorStorage>();
builder.Services.AddTransient<IOrganizerStorage, OrganizerStorage>(); builder.Services.AddTransient<IOrganizerStorage, OrganizerStorage>();

View File

@ -75,7 +75,10 @@
<input type="hidden" name="id" value="@Model.Id" /> <input type="hidden" name="id" value="@Model.Id" />
<button type="submit" class="btn btn-black btn-block" style="margin-bottom: 20px;">Отчет Word о посетителях</button> <button type="submit" class="btn btn-black btn-block" style="margin-bottom: 20px;">Отчет Word о посетителях</button>
</form> </form>
<a class="btn btn-dark btn-block mb-4" asp-action="ReportExcel" asp-route-id="@Model.Id">Отчет Excel о посетителях </a> <form method="post" asp-action="ReportExcel" asp-controller="Home">
<input type="hidden" name="id" value="@Model.Id" />
<button type="submit" class="btn btn-black btn-block" style="margin-bottom: 20px;">Отчет Excel о посетителях</button>
</form>
</div> </div>
</div> </div>
</div> </div>

View File

@ -29,9 +29,6 @@ namespace EventVisitorDatabase.Entities
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
[Required] [Required]
public string Phone { get; set; } = string.Empty; public string Phone { get; set; } = string.Empty;
public static OrganizerEntity? Create(OrganizerBindingModel model) public static OrganizerEntity? Create(OrganizerBindingModel model)
{ {
if (model == null) if (model == null)

View File

@ -11,6 +11,5 @@ namespace EventVisitorLogic.BindingModels
{ {
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;
public int EventId { get; set; } public int EventId { get; set; }
public List<VisitorViewModel> Visitors { get; set; } = new();
} }
} }

View File

@ -20,9 +20,15 @@ namespace EventVisitorLogic.OfficePackage
Text = info.Title, Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title StyleInfo = ExcelStyleInfoType.Title
}); });
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "F1"
});
uint rowIndex = 2; uint rowIndex = 2;
foreach (var pc in info.Visitors) foreach (var pc in info.Visitors)
{ {
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -30,27 +36,47 @@ namespace EventVisitorLogic.OfficePackage
Text = pc.Name, Text = pc.Name,
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.Text
}); });
InsertCellInWorksheet(new ExcelCellParameters MergeCells(new ExcelMergeParameters
{ {
ColumnName = "B", CellFromName = $"A{rowIndex}",
RowIndex = rowIndex, CellToName = $"B{rowIndex}"
Text = pc.Email,
StyleInfo = ExcelStyleInfoType.Text
}); });
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
RowIndex = rowIndex, RowIndex = rowIndex,
Text = pc.Phone, Text = pc.Email,
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.Text
}); });
MergeCells(new ExcelMergeParameters
{
CellFromName = $"C{rowIndex}",
CellToName = $"D{rowIndex}"
});
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "D", ColumnName = "E",
RowIndex = rowIndex,
Text = pc.Phone,
StyleInfo = ExcelStyleInfoType.Text
});
MergeCells(new ExcelMergeParameters
{
CellFromName = $"E{rowIndex}",
CellToName = $"F{rowIndex}"
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "G",
RowIndex = rowIndex, RowIndex = rowIndex,
Text = pc.Status, Text = pc.Status,
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.Text
}); });
MergeCells(new ExcelMergeParameters
{
CellFromName = $"G{rowIndex}",
CellToName = $"H{rowIndex}"
});
rowIndex++; rowIndex++;
} }
SaveExcel(info); SaveExcel(info);

View File

@ -1,4 +1,6 @@
using EventVisitorLogic.OfficePackage.HelperEnums; 
using DocumentFormat.OpenXml.Wordprocessing;
using EventVisitorLogic.OfficePackage.HelperEnums;
using EventVisitorLogic.OfficePackage.HelperModels; using EventVisitorLogic.OfficePackage.HelperModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -13,21 +15,43 @@ namespace EventVisitorLogic.OfficePackage
public void CreateDoc(WordInfo info) public void CreateDoc(WordInfo info)
{ {
CreateWord(info); CreateWord(info);
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, Texts = new List<(string, WordTextProperties)>
{
(info.Title, new WordTextProperties { Bold = true, Size = "24" })
},
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { ("", new WordTextProperties()) }, // Пустой параграф
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
// Добавление информации о посетителях
foreach (var km in info.Visitors) foreach (var km in info.Visitors)
{ {
// Создание параграфа для каждого посетителя с более красивым оформлением
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> 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})}, {
($"Имя: {km.Name} ", new WordTextProperties { Size = "20", Bold = true }),
($"{km.Email} ", new WordTextProperties { Size = "20" }),
($"{km.Phone} ", new WordTextProperties { Size = "20" }),
($"{km.Status}", new WordTextProperties { Size = "20" }),
},
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
@ -35,11 +59,23 @@ namespace EventVisitorLogic.OfficePackage
} }
}); });
// Добавление пробела между записями посетителей
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { ("", new WordTextProperties()) }, // Пустой параграф
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
} }
SaveWord(info); SaveWord(info);
} }
protected abstract void CreateWord(WordInfo info); protected abstract void CreateWord(WordInfo info);
protected abstract void CreateParagraph(WordParagraph paragraph); protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfo info); protected abstract void SaveWord(WordInfo info);
} }
} }

View File

@ -342,6 +342,7 @@ namespace EventVisitorLogic.OfficePackage.Implements
}; };
mergeCells.Append(mergeCell); mergeCells.Append(mergeCell);
} }
protected override void SaveExcel(ExcelInfo info) protected override void SaveExcel(ExcelInfo info)
{ {
if (_spreadsheetDocument == null) if (_spreadsheetDocument == null)
@ -349,7 +350,8 @@ namespace EventVisitorLogic.OfficePackage.Implements
return; return;
} }
_spreadsheetDocument.WorkbookPart!.Workbook.Save(); _spreadsheetDocument.WorkbookPart!.Workbook.Save();
//_spreadsheetDocument.Close(); _spreadsheetDocument.Dispose();
_spreadsheetDocument = null;
} }
} }
} }

View File

@ -107,14 +107,35 @@ namespace EventVisitorLogic.OfficePackage.Implements
} }
_docBody.AppendChild(docParagraph); _docBody.AppendChild(docParagraph);
} }
protected override void SaveWord(WordInfo info) protected override void SaveWord(WordInfo info)
{ {
// Проверьте, инициализированы ли _docBody и _wordDocument
if (_docBody == null || _wordDocument == null) if (_docBody == null || _wordDocument == null)
{ {
return; return;
} }
try
{
// Добавление свойств секции (если это необходимо)
_docBody.AppendChild(CreateSectionProperties()); _docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
// Сохранение документа
_wordDocument.MainDocumentPart.Document.Save();
}
catch (Exception ex)
{
// Логирование ошибки
Console.WriteLine($"Error saving document: {ex.Message}");
}
finally
{
// Закрытие документа с помощью Dispose
_wordDocument.Dispose(); // Освобождает ресурсы, связанные с документом
_wordDocument = null; // Сброс ссылки после освобождения
}
} }
} }