Files
WinFormDiApp/WinFormDi.BLR/ReadingIn.cs
2023-09-04 12:29:03 +02:00

141 lines
4.9 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using WinFormDiApp.BL.Helpers;
using WinFormDiApp.BLI;
using WinFormDiApp.BL.Models;
using Microsoft.Extensions.DependencyInjection;
namespace WinFormDiApp.BLR;
public class ReadingIn : IReadingIn
{
private readonly IConfiguration _configuration;
private readonly ILogger<ReadingIn> _logger;
private readonly IAccountRecordRepository _accountRecordRepository;
private readonly IExcellent _excellent;
public ReadingIn(
IConfiguration configuration,
ILogger<ReadingIn> logger,
IAccountRecordRepository accountRecordRepository,
IExcellent excellent)
{
_configuration = configuration;
_logger = logger;
_accountRecordRepository = accountRecordRepository;
_excellent = excellent;
}
// @"C:\dev\MyYearlyCountings\TransactionsTest.xls"
public IEnumerable<AccountRecord> readXLS(string FilePath)
{
List<AccountRecord> records = new List<AccountRecord>();
AccountRecord? record = null;
FileInfo existingFile = new FileInfo(FilePath);
var fieldNr = 0;
_excellent.ExcellentStart(existingFile.FullName, 1); ;
//get the first worksheet in the workbook
int colCount = _excellent.Columns;
int rowCount = _excellent.Rows; //get row count
bool prt = false;
for (int row = 0; row <= rowCount; row++)
{
if (prt)
{
//Console.WriteLine();
//// _logger.LogInformation("");
records.Add(record);
fieldNr = 0;
}
prt = false;
for (int col = 0; col <= colCount; col++)
{
var x = _excellent.ReadCell(row, col);
if (_excellent.ReadCell(row, col) == null)
{
// Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + "null");
}
else
{
if (col == 0 && _excellent.DataType == "DateTime")
{
prt = true;
record = new AccountRecord();
}
//Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value.ToString().Trim());
if (prt)
{
if (x == "") { }
else
{
fieldNr++;
// _logger.LogInformation($"{exObject.ReadCell(row, col).ToString().Trim()}/t");
switch (fieldNr)
{
case 1:
{
record.BetalDatum = DateTime.FromOADate(double.Parse(_excellent.ReadCell(row, col)));
break;
}
case 2:
{
record.Mottagare = _excellent.ReadCell(row, col).ToString().Trim();
break;
}
case 3:
{
record.Konto = _excellent.ReadCell(row, col).ToString().Trim();
break;
}
case 4:
{
record.Belopp = double.Parse(_excellent.ReadCell(row, col).ToString().Trim());
break;
}
case 5:
{
record.Avisering = _excellent.ReadCell(row, col).ToString().Trim();
break;
}
}
}
}
}
}
}
return records;
}
public bool ReadAndSaveInvoices(string fullFileName)
{
var result = true;
var restab = readXLS(fullFileName);
if (restab != null)
{
try
{
restab.ToList().ForEach(x =>
{
_accountRecordRepository.AddAccountRecord(x);
});
// restab.ToList().ForEach(x => { _accountRecordRepository.AddAccountRecord(x); });
}
catch (Exception ex)
{
_logger.LogError("MassUppdatering misslyckat: -->{iMessage}", ex.Message);
result = false;
}
}
return result;
}
}