174 lines
6.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using EmployeeManagmentBusinessLogic.BusinessLogic;
using EmployeeManagmentContracts.BusinessLogicContracts;
using EmployeeManagmentContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using Microsoft.Win32;
namespace EmployeeManagmentView.Employee.Vacation
{
/// <summary>
/// Логика взаимодействия для ViewVacationWindow.xaml
/// </summary>
public partial class ViewVacationWindow : Window
{
private readonly IVacationLogic _vacationLogic;
private readonly IEmployeeLogic _employeeLogic;
private readonly IPhisicalPersonLogic _phisicalPersonLogic;
private IEnumerable<VacationViewModel> _allVacations;
private List<EmployeeViewModel> _employees;
public ViewVacationWindow(IVacationLogic vacationLogic, IEmployeeLogic employeeLogic, IPhisicalPersonLogic phisicalPersonLogic)
{
_vacationLogic = vacationLogic;
_employeeLogic = employeeLogic;
_phisicalPersonLogic = phisicalPersonLogic;
InitializeComponent();
LoadVacations();
}
private void LoadVacations()
{
_allVacations = _vacationLogic.GetFullList(); // Загрузка всех данных
VacationsDataGrid.ItemsSource = _allVacations;
}
private void ExportToExcelButton_Click(object sender, RoutedEventArgs e)
{
try
{
var vacations = _vacationLogic.GetFullList();
if (vacations == null || !vacations.Any())
{
MessageBox.Show("Нет данных для экспорта.", "Внимание", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
// Открытие диалогового окна для сохранения файла
SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Excel файлы (*.xlsx)|*.xlsx",
Title = "Сохранить отчет об отпусках",
FileName = "Отчет_отпуска.xlsx"
};
if (saveFileDialog.ShowDialog() == true)
{
string filePath = saveFileDialog.FileName; // Путь и имя файла
GenerateExcelReport(filePath, vacations); // Генерация отчета
MessageBox.Show($"Отчет успешно сохранен: {filePath}", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка экспорта: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void GenerateExcelReport(string filePath, List<VacationViewModel> vacations)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
// Создаем Workbook
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
// Создаем Worksheet
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в Workbook
Sheets sheets = document.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet()
{
Id = document.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Отпуска"
};
sheets.Append(sheet);
// Получаем SheetData
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// Заполняем заголовки
Row headerRow = new Row();
headerRow.Append(
CreateTextCell("A", "ID"),
CreateTextCell("B", "Сотрудник"),
CreateTextCell("C", "Дата начала"),
CreateTextCell("D", "Дата окончания"),
CreateTextCell("E", "Статус")
);
sheetData.AppendChild(headerRow);
// Заполняем данные
foreach (var vacation in vacations)
{
Row row = new Row();
row.Append(
CreateTextCell("A", vacation.Id.ToString()),
CreateTextCell("B", vacation.EmployeeName),
CreateTextCell("C", vacation.StartData.ToString("dd.MM.yyyy")),
CreateTextCell("D", vacation.EndData.ToString("dd.MM.yyyy")),
CreateTextCell("E", vacation.Passed ? "Проведен" : "Не проведен")
);
sheetData.AppendChild(row);
}
workbookPart.Workbook.Save();
}
}
// Метод для создания текстовой ячейки
private Cell CreateTextCell(string columnName, string text)
{
return new Cell
{
DataType = CellValues.String,
CellReference = columnName,
CellValue = new CellValue(text)
};
}
private void SearchTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
string query = SearchTextBox.Text.ToLower();
if (string.IsNullOrWhiteSpace(query))
{
// Отображаем все записи
VacationsDataGrid.ItemsSource = _allVacations;
}
else
{
// Фильтрация по всем полям сущности
var filteredList = _allVacations.Where(vac =>
(vac.EmployeeName?.ToLower().Contains(query) ?? false) ||
(vac.StartData.ToString("dd.MM.yyyy").Contains(query)) ||
(vac.EndData.ToString("dd.MM.yyyy").Contains(query)) ||
(vac.Passed.ToString().ToLower().Contains(query))
).ToList();
VacationsDataGrid.ItemsSource = filteredList;
}
}
}
}