git_bsmd/ENI2/Excel/ExcelLocalImportHelper.cs

660 lines
28 KiB
C#

using bsmd.database;
using ClosedXML.Excel;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
namespace ENI2.Excel
{
internal static class ExcelLocalImportHelper
{
#region Last 10 Port Facilities Called Import from Excel
public static int ImportLast10PortFacilities(SEC sec)
{
int cnt = 0;
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var rows = worksheet.RangeUsed().RowsUsed();
int columnCount = worksheet.RangeUsed().ColumnCount();
// Check minimum columns upfront
if (columnCount < 8)
{
throw new InvalidDataException("Sheet must have at least 8 Columns of data");
}
List<LastTenPortFacilitiesCalled> importL10C = new List<LastTenPortFacilitiesCalled>();
foreach (var row in rows)
{
if (cnt >= 10) break; // Maximum 10 rows
// Skip empty rows
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
LastTenPortFacilitiesCalled l10c = new LastTenPortFacilitiesCalled();
try
{
// Column 1: Port Name
if (!row.Cell(1).IsEmpty())
l10c.PortFacilityPortName = row.Cell(1).GetString();
// Column 3: Country
if (!row.Cell(3).IsEmpty())
l10c.PortFacilityPortCountry = row.Cell(3).GetString();
// Column 4: Locode
if (!row.Cell(4).IsEmpty())
l10c.PortFacilityPortLoCode = row.Cell(4).GetString();
// Column 5: Arrival Date
if (!row.Cell(5).IsEmpty())
{
l10c.PortFacilityDateOfArrival = row.Cell(5).GetDateTime();
}
// Column 6: Departure Date
if (!row.Cell(6).IsEmpty())
{
l10c.PortFacilityDateOfDeparture = row.Cell(6).GetDateTime();
}
// Column 7: Security Level (byte)
if (!row.Cell(7).IsEmpty())
{
l10c.PortFacilityShipSecurityLevel = row.Cell(7).GetValue<byte>();
}
// Column 8: GISIS Code
if (!row.Cell(8).IsEmpty())
{
int gisis = row.Cell(8).GetValue<int>();
l10c.PortFacilityGISISCode = gisis.ToString().PadLeft(4, '0');
}
// Column 9: Security Matters (optional, can be beyond minimum columns)
if (columnCount >= 9 && !row.Cell(9).IsEmpty())
{
l10c.PortFacilitySecurityMattersToReport = row.Cell(9).GetString();
if (l10c.PortFacilitySecurityMattersToReport?.Equals("nil", StringComparison.OrdinalIgnoreCase) == true)
l10c.PortFacilitySecurityMattersToReport = null;
}
// Column 10: GISIS Code Locode (optional, can be beyond minimum columns)
if (columnCount >= 10 && !row.Cell(10).IsEmpty())
{
l10c.PortFacilityGISISCodeLocode = row.Cell(10).GetString();
}
l10c.SEC = sec;
l10c.IsDirty = true;
l10c.Identifier = LastTenPortFacilitiesCalled.GetNewIdentifier(sec.LastTenPortFacilitesCalled);
sec.LastTenPortFacilitesCalled.Add(l10c);
importL10C.Add(l10c);
cnt++;
}
catch (Exception ex)
{
throw new InvalidDataException($"Error processing row {row.RowNumber()}: {ex.Message}", ex);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError,
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return cnt;
}
#endregion
#region Last 30 days Import from Excel
public static int ImportLast30Days(MDH mdh)
{
int cnt = 0;
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var rows = worksheet.RangeUsed().RowsUsed();
int columnCount = worksheet.RangeUsed().ColumnCount();
List<PortOfCallLast30Days> importPoC30 = new List<PortOfCallLast30Days>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
if (columnCount < 3)
{
throw new InvalidDataException("Sheet must have at least 3 Columns of data");
}
PortOfCallLast30Days poc30 = new PortOfCallLast30Days();
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
// Safer locode extraction
if (!row.Cell(1).IsEmpty())
{
try
{
poc30.PortOfCallLast30DaysLocode = row.Cell(1).GetString();
}
catch (Exception ex)
{
throw new InvalidDataException($"Invalid locode in row {row.RowNumber()}: {ex.Message}");
}
}
// Safer date extraction
if (!row.Cell(2).IsEmpty())
{
try
{
poc30.PortOfCallLast30DaysDateOfDeparture = row.Cell(2).GetDateTime();
}
catch (Exception ex)
{
throw new InvalidDataException($"Invalid date in row {row.RowNumber()}: {ex.Message}");
}
}
// Safer boolean extraction
string boolString = "";
if (!row.Cell(3).IsEmpty())
{
boolString = row.Cell(3).GetString()?.Trim() ?? "";
}
poc30.PortOfCallLast30DaysCrewMembersJoined = (
boolString.Equals("y", StringComparison.OrdinalIgnoreCase) ||
boolString.Equals("yes", StringComparison.OrdinalIgnoreCase) ||
boolString.Equals("j", StringComparison.OrdinalIgnoreCase));
// FIX: Check column count before accessing column 4
if (columnCount >= 4)
{
string allNewCrew = row.Cell(4).IsEmpty() ? null : row.Cell(4).GetString()?.Trim();
if (!allNewCrew.IsNullOrEmpty())
{
string[] crewNames = allNewCrew.Split(',', ';');
foreach (string crewName in crewNames)
{
string trimmedName = crewName.Trim();
if (trimmedName.IsNullOrEmpty()) continue;
PortOfCallLast30DaysCrewJoinedShip poc30Crew = new PortOfCallLast30DaysCrewJoinedShip
{
PortOfCallLast30DaysCrewJoinedShipName = trimmedName,
PortOfCallLast30Days = poc30
};
poc30.CrewJoinedShip.Add(poc30Crew);
}
}
}
poc30.MDH = mdh;
mdh.PortOfCallLast30Days.Add(poc30);
importPoC30.Add(poc30);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError,
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return cnt;
}
#endregion
#region Waste from Excel
public static int ImportWaste(WAS was)
{
int cnt = 0;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xls;*.xlsx";
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(3); // Skip first three rows
List<Waste> importWasteList = new List<Waste>();
object o = null;
// Diese Funktion kann das "alte" Sheet Format nicht mehr einlesen!
foreach (var row in rows)
{
if (cnt >= 35) break; // Maximum 35 rows
if (worksheet.RangeUsed().ColumnCount() < 9)
{
throw new InvalidDataException("Sheet must have 9 Columns of data");
}
if (!row.Cell(2).IsEmpty()) o = row.Cell(2).Value; else o = null;
if ((o != null) && Int32.TryParse(o.ToString(), out int wasteType))
{
Waste waste = was.GetWasteForType(wasteType);
if (waste == null)
{
waste = new Waste();
waste.WasteType = wasteType;
waste.WAS = was;
waste.IsDirty = true;
waste.Identifier = Waste.GetNewIdentifier(was.Waste);
was.Waste.Add(waste);
}
else
{
waste.IsDirty = true;
}
if (!row.Cell(5).IsEmpty()) waste.WasteDescription = row.Cell(5).GetString();
if (waste.WasteDescription.IsNullOrEmpty())
waste.WasteDescription = "-";
if (!row.Cell(6).IsEmpty())
waste.WasteDisposalAmount_MTQ = row.Cell(6).GetDouble();
if (!row.Cell(7).IsEmpty())
waste.WasteCapacity_MTQ = row.Cell(7).GetDouble();
if (!row.Cell(8).IsEmpty()) waste.WasteAmountRetained_MTQ = row.Cell(8).GetDouble();
if (!row.Cell(9).IsEmpty())
waste.WasteDisposalPort = row.Cell(9).GetString().ToUpper();
if (!row.Cell(10).IsEmpty())
waste.WasteAmountGeneratedTillNextPort_MTQ = row.Cell(10).GetDouble();
importWasteList.Add(waste);
cnt++;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return cnt;
}
#endregion
#region WAS Exemptions Import from Excel
public static List<WASExemption> ImportWASExemptions()
{
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var range = worksheet.RangeUsed();
var rows = range.RowsUsed().Skip(1); // first row is header
int columnCount = range.ColumnCount();
if (columnCount < 5)
{
throw new InvalidDataException("Sheet must have at least 5 Columns of data");
}
List<WASExemption> exemptions = new List<WASExemption>();
foreach (var row in rows)
{
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty() && row.Cell(3).IsEmpty())
continue;
WASExemption was = new WASExemption();
if (!row.Cell(1).IsEmpty())
was.IMO = Truncate(row.Cell(1).GetString().Trim(), 7);
if (!row.Cell(2).IsEmpty())
was.ShipName = Truncate(row.Cell(2).GetString().Trim(), 100);
if (!row.Cell(3).IsEmpty())
was.Port = Truncate(row.Cell(3).GetString().Trim(), 5);
if (!row.Cell(4).IsEmpty())
was.ValidUntil = row.Cell(4).GetDateTime();
else
throw new InvalidDataException($"Missing ValidUntil value in row {row.RowNumber()}");
if (!row.Cell(5).IsEmpty())
was.Remarks = Truncate(row.Cell(5).GetString().Trim(), 255);
was.IsDirty = true;
exemptions.Add(was);
}
return exemptions;
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError,
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return new List<WASExemption>();
}
#endregion
#region Hazard Material Import from Excel
public static List<HAZPosTemplate> ImportHazardMaterials()
{
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var range = worksheet.RangeUsed();
var rows = range.RowsUsed().Skip(1); // header row
List<HAZPosTemplate> templates = new List<HAZPosTemplate>();
foreach (var row in rows)
{
if (row.Cell(1).IsEmpty() &&
row.Cell(3).IsEmpty() &&
row.Cell(5).IsEmpty())
continue;
HAZPosTemplate hpt = new HAZPosTemplate();
if (!row.Cell(1).IsEmpty())
hpt.Description = Truncate(row.Cell(1).GetString().Trim(), 100);
int? hazardIndex = GetIntCell(row.Cell(3));
if (hazardIndex.HasValue)
hpt.Hazard = (HAZPosTemplate.HazardsEnum)hazardIndex.Value;
int? flashpointIndex = GetIntCell(row.Cell(5));
if (flashpointIndex.HasValue)
hpt.Flashpoint = (HAZPosTemplate.FlashpointEnum)flashpointIndex.Value;
if (!row.Cell(6).IsEmpty())
{
string specRef = row.Cell(6).GetString().Trim();
if (specRef.Equals("Ja", StringComparison.OrdinalIgnoreCase))
hpt.SpecRef15_19 = true;
else if (specRef.Equals("Nein", StringComparison.OrdinalIgnoreCase))
hpt.SpecRef15_19 = false;
}
if (!row.Cell(7).IsEmpty())
{
string type = row.Cell(7).GetString().Trim();
if (Enum.TryParse(type, true, out HAZPosTemplate.SublistType templateType))
hpt.TemplateType = templateType;
}
if (!row.Cell(9).IsEmpty())
{
string mhb = row.Cell(9).GetString().Trim();
if (mhb.Equals("y", StringComparison.OrdinalIgnoreCase))
hpt.MHB = true;
else if (mhb.Equals("n", StringComparison.OrdinalIgnoreCase))
hpt.MHB = false;
}
int? imsbcHazIndex = GetIntCell(row.Cell(12));
if (imsbcHazIndex.HasValue)
hpt.IMSBC_HAZ = (HAZPosTemplate.IMO_HAZ_ClassEnum)imsbcHazIndex.Value;
if (!row.Cell(13).IsEmpty())
hpt.UNNr = Truncate(row.Cell(13).GetString().Trim(), 100);
if (!row.Cell(14).IsEmpty())
hpt.IMOClass = Truncate(row.Cell(14).GetString().Trim(), 100);
int? pollutionIndex = GetIntCell(row.Cell(16));
if (pollutionIndex.HasValue)
hpt.PollutionCategory = (HAZPosTemplate.PollutionCategoryEnum)pollutionIndex.Value;
if (!row.Cell(20).IsEmpty())
hpt.FP_IBC = Truncate(row.Cell(20).GetString().Trim(), 100);
if (!row.Cell(21).IsEmpty())
hpt.Comment = Truncate(row.Cell(21).GetString().Trim(), 255);
hpt.IsDirty = true;
templates.Add(hpt);
}
return templates;
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError,
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return new List<HAZPosTemplate>();
}
#endregion
#region Port Areas Import from Excel
public static List<PortArea> ImportPortAreas()
{
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var range = worksheet.RangeUsed();
var rows = range.RowsUsed().Skip(1); // header row
List<PortArea> items = new List<PortArea>();
foreach (var row in rows)
{
if (row.Cell(1).IsEmpty() &&
row.Cell(2).IsEmpty() &&
row.Cell(3).IsEmpty() &&
row.Cell(4).IsEmpty() &&
row.Cell(5).IsEmpty())
continue;
PortArea pa = new PortArea
{
IsDirty = true
};
if (!row.Cell(1).IsEmpty())
pa.Country = Truncate(row.Cell(1).GetString().Trim(), 10);
if (!row.Cell(2).IsEmpty())
pa.Locode = Truncate(row.Cell(2).GetString().Trim(), 5);
if (!row.Cell(3).IsEmpty())
pa.Port = Truncate(row.Cell(3).GetString().Trim(), 255);
if (!row.Cell(4).IsEmpty())
pa.Code = Truncate(row.Cell(4).GetString().Trim(), 10);
if (!row.Cell(5).IsEmpty())
pa.Name = Truncate(row.Cell(5).GetString().Trim(), 255);
if (!row.Cell(6).IsEmpty())
pa.Agency = Truncate(row.Cell(6).GetString().Trim(), 255);
if (!row.Cell(7).IsEmpty())
pa.Berth = Truncate(row.Cell(7).GetString().Trim(), 255);
if (!row.Cell(8).IsEmpty())
pa.Ships = Truncate(row.Cell(8).GetString().Trim(), 255);
if (!row.Cell(9).IsEmpty())
pa.Remarks = Truncate(row.Cell(9).GetString().Trim(), 255);
items.Add(pa);
}
return items;
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError,
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return new List<PortArea>();
}
#endregion
#region LADG NST2007 Import from Excel
public static List<LADG_NST2007> ImportLADGNST2007()
{
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var range = worksheet.RangeUsed();
var rows = range.RowsUsed().Skip(1); // header row
List<LADG_NST2007> items = new List<LADG_NST2007>();
foreach (var row in rows)
{
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty())
continue;
LADG_NST2007 item = new LADG_NST2007
{
IsDirty = true
};
if (!row.Cell(1).IsEmpty())
item.NST2007 = Truncate(row.Cell(1).GetString().Trim(), 3);
if (!row.Cell(2).IsEmpty())
item.Description = Truncate(row.Cell(2).GetString().Trim(), 100);
items.Add(item);
}
return items;
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError,
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return new List<LADG_NST2007>();
}
#endregion
private static string Truncate(string value, int maxLength)
{
if (value == null)
return null;
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
private static int? GetIntCell(IXLCell cell)
{
if (cell == null || cell.IsEmpty()) return null;
try
{
return cell.GetValue<int>();
}
catch
{
string text = cell.GetString().Trim();
if (int.TryParse(text, out int val))
return val;
}
return null;
}
}
}