Ä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<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
{
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 MyYearlyCountings.Helpers;
using MyYearlyCountings.Repositories;
using OfficeOpenXml;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
//using Excel = Microsoft.Office.Interop.Excel;
namespace MyYearlyCountings.Facades;
@ -25,78 +26,69 @@ public class ReadingIn : IReadingIn
}
// @"C:\dev\MyYearlyCountings\TransactionsTest.xls"
public IEnumerable<AccountRecord> ReadExcelInvoices(string fullFileName)
public IEnumerable<AccountRecord> readXLS(string FilePath)
{
List<AccountRecord> records = new List<AccountRecord>();
AccountRecord? record = null;
Excel.Application xlApp = new Excel.Application();
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++)
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
//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++)
{
if (prt)
{
Console.Write("\r\n");
Console.WriteLine();
records.Add(record);
}
prt = false;
}
//write the value to the console
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 ((j == 1) && xx.IsNumeric())
if (worksheet.Cells[row, col].Value == null)
{
DateTime dt = DateTime.FromOADate(xlRange.Cells[i, j].Value2);
prt = true;
if (prt)
{
Console.Write(dt.ToShortDateString() + "\t");
record = new AccountRecord();
record.BetalDatum = dt;
}
// Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + "null");
}
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)
{
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
switch (j)
Console.Write($"{worksheet.Cells[row, col].Value.ToString().Trim()}/t");
switch (col)
{
case 1:
{
record.BetalDatum = DateTime.Parse( worksheet.Cells[row, col].Value.ToString().Trim());
break;
}
case 3:
{
record.Mottagare = xlRange.Cells[i, j].Value2.ToString();
record.Mottagare = worksheet.Cells[row, col].Value.ToString().Trim();
break;
}
case 5:
{
record.Konto = xlRange.Cells[i, j].Value2.ToString();
record.Konto = worksheet.Cells[row, col].Value.ToString().Trim();
break;
}
case 7:
{
record.Belopp = xlRange.Cells[i, j].Value2;
record.Belopp = double.Parse(worksheet.Cells[row, col].Value.ToString().Trim());
break;
}
case 9:
{
record.Avisering = xlRange.Cells[i, j].Value2.ToString();
record.Avisering = worksheet.Cells[row, col].Value.ToString().Trim();
break;
}
@ -104,43 +96,21 @@ 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;
}
public bool ReadAndSaveInvoices(string fullFileName)
{
var result = true;
var restab = ReadExcelInvoices(fullFileName);
var restab = readXLS(fullFileName);
if (restab != null)
{
try
{
restab.ToList().ForEach(x => {
restab.ToList().ForEach(x =>
{
_accountRecordRepository.AddAccountRecord(x);
});

View File

@ -11,4 +11,16 @@ public static class Extensions
}
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>
<ItemGroup>
<COMReference Include="Microsoft.Office.Interop.Excel">
<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="EPPlus" Version="6.2.4" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
@ -47,7 +36,7 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Local.db">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

View File

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

View File

@ -6,8 +6,8 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyYearlyCountings.UI
{
namespace MyYearlyCountings.UI;
public class KeyHandling
{
private readonly IConfiguration _configuration;
@ -20,4 +20,3 @@ namespace MyYearlyCountings.UI
}
}
}

View File

@ -41,12 +41,18 @@ public class Worker
{
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}"));
}
}
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
{
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": {
"DefaultConnection": "Data Source=.\\Local.db"
}

BIN
TransactionsTest.xlsx Normal file

Binary file not shown.