Merge branch 'feature/import_ships' into develop

This commit is contained in:
Daniel Schick 2023-08-31 13:52:44 +02:00
commit 6acc47d158
3 changed files with 75 additions and 1 deletions

Binary file not shown.

Binary file not shown.

View File

@ -672,9 +672,83 @@ namespace RoleEditor
}
}
private void buttonImportShipss_Click(object sender, RoutedEventArgs e)
private async void buttonImportShipss_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<Ship> importShipList = new();
int bCounter = 0;
int pCounter = 0;
try
{
do
{
while (reader.Read())
{
if (reader.FieldCount < 4)
{
throw new InvalidDataException("Sheet must have at least 4 Columns of data");
}
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
string ship_name = "";
if (!reader.IsDBNull(0)) ship_name = reader.GetString(0);
if (ship_name.Equals("Name", StringComparison.OrdinalIgnoreCase)) continue;
// find ship in existing list
if (_ships.Any(predicate: x => (x.Name != null) && x.Name.Equals(ship_name, StringComparison.OrdinalIgnoreCase)))
continue;
Ship s = new();
s.Name = ship_name;
if (!reader.IsDBNull(1))
s.IMO = (int) reader.GetDouble(1);
if (!reader.IsDBNull(2))
s.Length = reader.GetDouble(2);
if(!reader.IsDBNull(3))
s.Width = reader.GetDouble(3);
await s.Save(_dbManager);
_ships.Add(s);
bCounter++;
}
} while (reader.NextResult());
if ((pCounter > 0) || (bCounter > 0))
{
MessageBox.Show($"Imported {bCounter} ships");
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
stream.Close();
}
}
#endregion