From 66c0dcc6c69bb6849b7e9108dd59af5fac17a0e7 Mon Sep 17 00:00:00 2001
From: maksim <kashin20031984@mail.ru>
Date: Sun, 8 Dec 2024 18:01:44 +0400
Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?=
 =?UTF-8?q?=D0=BD=D0=BE=20=D0=BE=D0=BA=D0=BD=D0=BE=20=D0=B4=D0=BB=D1=8F=20?=
 =?UTF-8?q?excel?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../Employee/Salary/ViewSalaryWindow.xaml.cs  |  20 +++-
 .../Employee/Vacation/ViewVacationWindow.xaml |   1 +
 .../Vacation/ViewVacationWindow.xaml.cs       | 106 +++++++++++++++++-
 3 files changed, 121 insertions(+), 6 deletions(-)

diff --git a/EmployeeManagmentView/Employee/Salary/ViewSalaryWindow.xaml.cs b/EmployeeManagmentView/Employee/Salary/ViewSalaryWindow.xaml.cs
index ea9729c..872bf8f 100644
--- a/EmployeeManagmentView/Employee/Salary/ViewSalaryWindow.xaml.cs
+++ b/EmployeeManagmentView/Employee/Salary/ViewSalaryWindow.xaml.cs
@@ -17,6 +17,7 @@ using System.Windows.Input;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using System.IO;
+using Microsoft.Win32;
 
 
 namespace EmployeeManagmentView.Employee.Salary
@@ -57,11 +58,22 @@ namespace EmployeeManagmentView.Employee.Salary
                     return;
                 }
 
-                // Генерация Excel-файла
-                string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Отчет_зарплаты.xlsx");
-                GenerateExcelReport(filePath, salaries);
+                // Открытие диалогового окна для сохранения файла
+                SaveFileDialog saveFileDialog = new SaveFileDialog
+                {
+                    Filter = "Excel файлы (*.xlsx)|*.xlsx",  // фильтр для файлов .xlsx
+                    Title = "Сохранить отчет об зарплатах",  // заголовок окна
+                    FileName = "Отчет_зарплат.xlsx"  // имя по умолчанию
+                };
+
+                // Проверка, что пользователь выбрал путь и имя файла
+                if (saveFileDialog.ShowDialog() == true)
+                {
+                    string filePath = saveFileDialog.FileName;  // Путь и имя файла
+                    GenerateExcelReport(filePath, salaries);  // Генерация отчета
+                    MessageBox.Show($"Отчет успешно сохранен: {filePath}", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
+                }
 
-                MessageBox.Show($"Отчет успешно сохранен: {filePath}", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
             }
             catch (Exception ex)
             {
diff --git a/EmployeeManagmentView/Employee/Vacation/ViewVacationWindow.xaml b/EmployeeManagmentView/Employee/Vacation/ViewVacationWindow.xaml
index da44b9c..0cebd43 100644
--- a/EmployeeManagmentView/Employee/Vacation/ViewVacationWindow.xaml
+++ b/EmployeeManagmentView/Employee/Vacation/ViewVacationWindow.xaml
@@ -45,6 +45,7 @@
                 HorizontalAlignment="Center" VerticalAlignment="Bottom"
                 Width="150" Height="40"
                 Margin="0,0,0,20"
+                Click="ExportToExcelButton_Click"
                 Background="#004890"
                 Foreground="White"
                 Style="{StaticResource RoundedButtonStyle}" />
diff --git a/EmployeeManagmentView/Employee/Vacation/ViewVacationWindow.xaml.cs b/EmployeeManagmentView/Employee/Vacation/ViewVacationWindow.xaml.cs
index bac5e42..48b2480 100644
--- a/EmployeeManagmentView/Employee/Vacation/ViewVacationWindow.xaml.cs
+++ b/EmployeeManagmentView/Employee/Vacation/ViewVacationWindow.xaml.cs
@@ -1,4 +1,7 @@
-using EmployeeManagmentBusinessLogic.BusinessLogic;
+using DocumentFormat.OpenXml.Packaging;
+using DocumentFormat.OpenXml.Spreadsheet;
+using DocumentFormat.OpenXml;
+using EmployeeManagmentBusinessLogic.BusinessLogic;
 using EmployeeManagmentContracts.BusinessLogicContracts;
 using EmployeeManagmentContracts.ViewModels;
 using System;
@@ -13,7 +16,8 @@ using System.Windows.Documents;
 using System.Windows.Input;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
-using System.Windows.Shapes;
+using System.IO;
+using Microsoft.Win32;
 
 namespace EmployeeManagmentView.Employee.Vacation
 {
@@ -44,6 +48,104 @@ namespace EmployeeManagmentView.Employee.Vacation
             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)
         {