Ändrad inläsningsmetod för Xlsx

This commit is contained in:
2023-06-04 23:28:20 +02:00
parent ced65ad4b7
commit 0e8c8f179c
14 changed files with 155 additions and 98 deletions

View File

@ -22,5 +22,9 @@ public class DataContext : DbContext
public DbSet<Member> Members { get; set; } public DbSet<Member> Members { get; set; }
public DbSet<AccountRecord> AccountRecords { get; set; } public DbSet<AccountRecord> AccountRecords { get; set; }
public DbSet<CalYear> CalYears { get; set; }
public DbSet<CalMonth> CalMonths { get; set; }
public DbSet<CalDay> CalDays { get; set; }
public DbSet<CalHour> CalHours { get; set; }
} }

View File

@ -3,6 +3,6 @@
public interface IReadingIn public interface IReadingIn
{ {
bool ReadAndSaveInvoices(string fullFileName); bool ReadAndSaveInvoices(string fullFileName);
IEnumerable<AccountRecord> ReadExcelInvoices(string fullFileName); IEnumerable<AccountRecord> readXLS(string FilePath);
} }
} }

View File

@ -2,8 +2,9 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MyYearlyCountings.Helpers; using MyYearlyCountings.Helpers;
using MyYearlyCountings.Repositories; using MyYearlyCountings.Repositories;
using OfficeOpenXml;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel; //using Excel = Microsoft.Office.Interop.Excel;
namespace MyYearlyCountings.Facades; namespace MyYearlyCountings.Facades;
@ -25,78 +26,69 @@ public class ReadingIn : IReadingIn
} }
// @"C:\dev\MyYearlyCountings\TransactionsTest.xls" // @"C:\dev\MyYearlyCountings\TransactionsTest.xls"
public IEnumerable<AccountRecord> ReadExcelInvoices(string fullFileName)
public IEnumerable<AccountRecord> readXLS(string FilePath)
{ {
List<AccountRecord> records = new List<AccountRecord>(); List<AccountRecord> records = new List<AccountRecord>();
AccountRecord? record = null; AccountRecord? record = null;
FileInfo existingFile = new FileInfo(FilePath);
Excel.Application xlApp = new Excel.Application(); using (ExcelPackage package = new ExcelPackage(existingFile))
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fullFileName);
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
var rowCount = xlRange.Rows.Count;
var colCount = xlRange.Columns.Count;
var prt = false;
//iterate over the rows and columns and print to the console as it appears in the file
//excel is not zero based!!
for (int i = 1; i <= rowCount; i++)
{ {
for (int j = 1; j <= colCount; j++) //get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
bool prt = false;
for (int row = 1; row <= rowCount; row++)
{ {
//new line if (prt)
if (j == 1)
{ {
if (prt) Console.WriteLine();
{ records.Add(record);
Console.Write("\r\n");
records.Add(record);
}
prt = false;
} }
//write the value to the console prt = false;
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) for (int col = 1; col <= colCount; col++)
{ {
string xx = xlRange.Cells[i, j].Value2.ToString(); if (worksheet.Cells[row, col].Value == null)
if ((j == 1) && xx.IsNumeric())
{ {
DateTime dt = DateTime.FromOADate(xlRange.Cells[i, j].Value2); // Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + "null");
prt = true;
if (prt)
{
Console.Write(dt.ToShortDateString() + "\t");
record = new AccountRecord();
record.BetalDatum = dt;
}
} }
else else
{ {
if (col == 1 && worksheet.Cells[row, col].Value.ToString().IsDate())
{
prt = true;
record = new AccountRecord();
}
//Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value.ToString().Trim());
if (prt) if (prt)
{ {
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t"); Console.Write($"{worksheet.Cells[row, col].Value.ToString().Trim()}/t");
switch (j) switch (col)
{ {
case 1:
{
record.BetalDatum = DateTime.Parse( worksheet.Cells[row, col].Value.ToString().Trim());
break;
}
case 3: case 3:
{ {
record.Mottagare = xlRange.Cells[i, j].Value2.ToString(); record.Mottagare = worksheet.Cells[row, col].Value.ToString().Trim();
break; break;
} }
case 5: case 5:
{ {
record.Konto = xlRange.Cells[i, j].Value2.ToString(); record.Konto = worksheet.Cells[row, col].Value.ToString().Trim();
break; break;
} }
case 7: case 7:
{ {
record.Belopp = xlRange.Cells[i, j].Value2; record.Belopp = double.Parse(worksheet.Cells[row, col].Value.ToString().Trim());
break; break;
} }
case 9: case 9:
{ {
record.Avisering = xlRange.Cells[i, j].Value2.ToString(); record.Avisering = worksheet.Cells[row, col].Value.ToString().Trim();
break; break;
} }
@ -104,47 +96,25 @@ public class ReadingIn : IReadingIn
} }
} }
} }
//add useful things here!
} }
} }
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
//rule of thumb for releasing com objects:
// never use two dots, all COM objects must be referenced and released individually
// ex: [somthing].[something].[something] is bad
//release com objects to fully kill excel process from running in the background
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
//close and release
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
return records; return records;
} }
public bool ReadAndSaveInvoices(string fullFileName) public bool ReadAndSaveInvoices(string fullFileName)
{ {
var result = true; var result = true;
var restab = ReadExcelInvoices(fullFileName); var restab = readXLS(fullFileName);
if (restab != null) if (restab != null)
{ {
try try
{ {
restab.ToList().ForEach(x => { restab.ToList().ForEach(x =>
_accountRecordRepository.AddAccountRecord(x); {
_accountRecordRepository.AddAccountRecord(x);
}); });
// restab.ToList().ForEach(x => { _accountRecordRepository.AddAccountRecord(x); }); // restab.ToList().ForEach(x => { _accountRecordRepository.AddAccountRecord(x); });
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -11,4 +11,16 @@ public static class Extensions
} }
else return false; else return false;
} }
public static bool IsDate(this string value) {
if (!string.IsNullOrEmpty(value) && value.Length<20)
{
if (DateTime.TryParse(value, out DateTime date))
{
return true;
}
else return false;
}
else return false;
}
} }

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyYearlyCountings.Models
{
public class CalDay
{
public int Id { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public string DayName { get; set; } = string.Empty;
public string DayComment { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyYearlyCountings.Models
{
public class CalHour
{
public int Id { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public int Hour { get; set; }
public string HourComment { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyYearlyCountings.Models
{
public class CalMonth
{
public int Id { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public string MonthName { get; set; } = string.Empty;
public string MonthComment { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyYearlyCountings.Models
{
public class CalYear
{
public int Id { get; set; }
public int Year { get; set; }
public string YearComment { get; set; } = string.Empty;
}
}

View File

@ -10,18 +10,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<COMReference Include="Microsoft.Office.Interop.Excel"> <PackageReference Include="EPPlus" Version="6.2.4" />
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>9</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>00020813-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
@ -47,7 +36,7 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
<None Update="Local.db"> <None Update="Local.db">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
</ItemGroup> </ItemGroup>

View File

@ -8,6 +8,9 @@ using Microsoft.Extensions.Hosting;
using MyYearlyCountings.Repositories; using MyYearlyCountings.Repositories;
using MyYearlyCountings.Data; using MyYearlyCountings.Data;
using MyYearlyCountings.Facades; using MyYearlyCountings.Facades;
using OfficeOpenXml;
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
IHost host = CreateHostBuilder(args).Build(); IHost host = CreateHostBuilder(args).Build();
var worker = ActivatorUtilities.CreateInstance<Worker>((IServiceProvider)host.Services); var worker = ActivatorUtilities.CreateInstance<Worker>((IServiceProvider)host.Services);

View File

@ -6,18 +6,17 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace MyYearlyCountings.UI namespace MyYearlyCountings.UI;
public class KeyHandling
{ {
public class KeyHandling private readonly IConfiguration _configuration;
private readonly ILogger<KeyHandling> _logger;
public KeyHandling(IConfiguration configuration, ILogger<KeyHandling> logger)
{ {
private readonly IConfiguration _configuration; _configuration = configuration;
private readonly ILogger<KeyHandling> _logger; _logger = logger;
public KeyHandling(IConfiguration configuration, ILogger<KeyHandling> logger)
{
_configuration = configuration;
_logger = logger;
}
} }
} }

View File

@ -41,12 +41,18 @@ public class Worker
{ {
if (_configuration["UI"] == "XLS") if (_configuration["UI"] == "XLS")
{ {
if (!_readingIn.ReadAndSaveInvoices(@"C:\dev\MyYearlyCountings\TransactionsTest.xls")) if (!_readingIn.ReadAndSaveInvoices(@"C:\dev\MyYearlyCountings\TransactionsTest.xlsx"))
{ {
var resUlt = _readingIn.ReadExcelInvoices(@"C:\dev\MyYearlyCountings\TransactionsTest.xls"); var resUlt = _readingIn.readXLS(@"C:\dev\MyYearlyCountings\TransactionsTest.xlsx");
resUlt.ToList().ForEach(rec => _logger.LogInformation($"Konto :{rec.Konto}, {rec.Belopp}")); resUlt.ToList().ForEach(rec => _logger.LogInformation($"Konto :{rec.Konto}, {rec.Belopp}"));
} }
} }
else if(_configuration["UI"] == "XLSNEW")
{
var records = _readingIn.readXLS(@"C:\dev\MyYearlyCountings\TransactionsTest.xlsx");
records.ToList().ForEach(rec => _logger.LogInformation($"Konto :{rec.Konto}, {rec.Belopp}"));
records.ToList().ForEach(rec => _accountRecordRepository.AddAccountRecord(rec));
}
else else
{ {
var ar = new AccountRecord { Konto = "BG 0867-4533", Mottagare = "NoOne", Belopp = 1270.34, BetalDatum = DateTime.Now.AddDays(10), Avisering = "Efaktura" }; var ar = new AccountRecord { Konto = "BG 0867-4533", Mottagare = "NoOne", Belopp = 1270.34, BetalDatum = DateTime.Now.AddDays(10), Avisering = "Efaktura" };

View File

@ -1,4 +1,9 @@
{ {
"EPPlus": {
"ExcelPackage": {
"LicenseContext": "Polyform NonCommercial" //The license context used
}
},
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Data Source=.\\Local.db" "DefaultConnection": "Data Source=.\\Local.db"
} }

BIN
TransactionsTest.xlsx Normal file

Binary file not shown.