Commit fd2e4918 by zry

init

parent fe46160f
This diff was suppressed by a .gitattributes entry.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Performance.DtoModels;
using Performance.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Performance.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DefaultController : ControllerBase
{
ILogger<DefaultController> _logger;
PerExcelService _excelService;
UserService _userService;
public DefaultController(PerExcelService excelService,
UserService userService,
ILogger<DefaultController> logger)
{
_excelService = excelService;
_userService = userService;
_logger = logger;
}
[HttpGet]
public ActionResult<PerExcel> Get()
{
var sd = _userService.GetUser();
_logger.LogDebug("debug", "aaaaaa");
var excel = _excelService.Analyze(@"C:\Users\ry\Desktop\文件\测试.xlsx");
return excel;
}
}
}
\ No newline at end of file
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Performance.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="MySql.Data" Version="8.0.15" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.15" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
<PackageReference Include="NLog" Version="4.5.11" />
<PackageReference Include="NLog.Extensions.Logging" Version="1.4.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Performance.Api
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:5001",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Performance.Api": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
"applicationUrl": "http://localhost:5001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
\ No newline at end of file
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NLog;
using NLog.Extensions.Logging;
using NLog.Web;
using Performance.DtoModels.AppSettings;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Repository;
using Performance.Services;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
namespace Performance.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(json =>
{
json.SerializerSettings.Converters.Add(new IsoDateTimeConverterContent() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
json.SerializerSettings.ContractResolver = new LowercaseContractResolver();
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include;
json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
json.SerializerSettings.Culture = new CultureInfo("it-IT");
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddPerformanceService();
services.Configure<AppConnection>(Configuration.GetSection("AppConnection"));
services.AddOptions<AppConnection>("AppConnection");
var connection = services.BuildServiceProvider().GetService<IOptions<AppConnection>>();
services.AddDbContext<PerformanceDbContext>(options =>
{
options.UseMySQL(connection.Value.PerformanceConnectionString);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog();
env.ConfigureNLog("nlog.config");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"AppConnection": {
"PerformanceConnectionString": "server=192.168.18.166;database=db_performance;uid=root;pwd=1234qwer;pooling=true;charset=utf8;convert zero datetime=true;port=3306;connection timeout=120;max pool size=512;allow user variables=true;"
}
}
<?xml version="1.0" encoding="utf-8"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info"
internalLogFile="c:\Temp\GrapefruitVuCore\internal-nlog.txt">
<!-- enable asp.net core and mongodb layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
<add assembly="NLog.Mongo"/>
</extensions>
<!--internal-nlog:NLog启动及加载config信息-->
<!--nlog-all:所有日志记录信息-->
<!--nlog-own:自定义日志记录信息-->
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="${basedir}/Logs/${shortdate}/${level}.log"
layout="日志记录时间:${longdate}${newline}日志级别:${uppercase:${level}}${newline}日志来源:${logger}${newline}日志信息:${message}${newline}错误信息:${exception:format=tostring}${newline}==============================================================${newline}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="${basedir}/Logs/${shortdate}/${level}.log"
layout="日志记录时间:${longdate}${newline}日志级别:${uppercase:${level}}${newline}日志来源:${logger}${newline}日志信息:${message}${newline}错误信息:${exception:format=tostring}${newline}url: ${aspnet-request-url}${newline}action: ${aspnet-mvc-action}${newline}==============================================================${newline}" />
<!-- write log to mongodb-->
<target xsi:type="Mongo"
name="mongo" databaseName="nlog"
collectionName="Logs"
connectionString="mongodb://172.31.216.37:27017/nlog"
cappedCollectionSize="26214400">
<property name="LongDate" layout="${longdate}" bsonType="DateTime" />
<property name="Level" layout="${level}" />
<property name="Logger" layout="${logger}"/>
<property name="Message" layout="${message}" />
<property name="Exception" layout="${exception:format=tostring}" />
<property name="Url" layout="${aspnet-request-url}" />
<property name="Action" layout="${aspnet-mvc-action}" />
<property name="UserName" layout="${windows-identity}" />
</target>
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxLevel="Info" final="true" />
<!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
<!--Add logs to mongodb-->
<logger name="*" minlevel="Trace" writeTo="mongo"/>
</rules>
</nlog>
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.Services\Performance.Services.csproj" />
</ItemGroup>
</Project>
using Performance.Services;
using System;
namespace Performance.ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
PerSheetService perSheetService = new PerSheetService();
PerExcelService perExcelService = new PerExcelService(perSheetService);
var excel = perExcelService.Analyze(@"C:\Users\ry\Desktop\文件\测试.xlsx");
Console.ReadKey();
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.EntityModels\Performance.EntityModels.csproj" />
</ItemGroup>
</Project>
using Microsoft.EntityFrameworkCore;
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Repository
{
public class PerformanceDbContext : DbContext
{
public DbSet<Sys_User> Sys_User { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels.AppSettings
{
public class AppConnection
{
public string PerformanceConnectionString { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels.AppSettings
{
public interface IAppSetting
{
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace Performance.DtoModels
{
public enum ExcelVersion
{
xlsx,
xls
}
public enum SheetType
{
[Description("无法识别")]
Unidentifiable = 1,
[Description("医院人员")]
Employee = 2,
[Description("收入")]
Income = 3,
[Description("支出")]
Expend = 4,
[Description("加班")]
Overtime = 5,
[Description("工作量")]
Workload = 6,
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
public class PerData
{
public string StandardName { get; set; }
public string Department { get; set; }
public string TypeName { get; set; }
public decimal CellValue { get; set; }
public string Annotation { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
public class PerDataExpend : PerData
{
public string ParentType { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
public class PerDataWorkload : PerData
{
public string ParentType { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Performance.DtoModels
{
public class PerExcel
{
public string Path { get; set; }
public ExcelVersion Version { get; set; }
public string FileName { get; set; }
public List<PerSheet> PerSheet { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Performance.DtoModels
{
public class PerHeader
{
public int PointRow { get; set; }
public int PointCell { get; set; }
public bool IsMerge => MergeRow > 1 || MergeCell > 1;
public int MergeRow { get; set; }
public int MergeCell { get; set; }
public string CellName { get; set; }
public int Level { get; set; }
public bool IsHasChildren => Children != null && Children.Any();
public List<PerHeader> Children { get; set; }
public PerHeader Parent { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
public class PerSheet
{
/// <summary>
/// sheet名称
/// </summary>
public string SheetName { get; set; }
/// <summary>
/// sheet模板类型
/// </summary>
public SheetType SheetType { get; set; }
/// <summary>
/// sheet模块名称
/// </summary>
public string ModuleName { get; set; }
/// <summary>
/// sheet数据
/// </summary>
public List<PerData> PerData { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.DtoModels
{
/// <summary>
/// excel读取数据位置信息
/// </summary>
public class PerSheetPoint
{
/// <summary>
/// 列头开始行(0开始)
/// </summary>
public int? HeaderFirstRowNum { get; set; }
/// <summary>
/// 列头结束行(0开始)
/// </summary>
public int? HeaderLastRowNum { get; set; }
/// <summary>
/// 列头开始列(0开始)
/// </summary>
public int? HeaderFirstCellNum { get; set; }
/// <summary>
/// 数据开始行
/// </summary>
public int? DataFirstRowNum { get; set; }
/// <summary>
/// 系数行号
/// </summary>
public int? FactorRow { get; set; }
/// <summary>
/// 核算单元列
/// </summary>
public int? StandardCellNum { get; set; }
public int? DeptCellNum { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.EntityModels
{
public class Allot
{
public int ID { get; set; }
public int HospitalId { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public decimal AllocationFee { get; set; }
public DateTime CreateDatetime { get; set; }
public string Path { get; set; }
public DateTime UploadDate { get; set; }
public int States { get; set; }
}
}
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.EntityModels
{
public class PerformanceDbContext : DbContext
{
public PerformanceDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Sys_User> Sys_User { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.EntityModels
{
public class Im_Expend
{
public int ID { get; set; }
public int SheetID { get; set; }
public string StandardName { get; set; }
public string Department { get; set; }
public string TypeName { get; set; }
public string ParentType { get; set; }
public decimal CellValue { get; set; }
public string Annotation { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.EntityModels
{
public class Im_SheetData
{
public int ID { get; set; }
public int AllotID { get; set; }
public string SheetName { get; set; }
public int SheetType { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.0" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.EntityModels
{
public class Sys_Hosptail
{
public int ID { get; set; }
public string HospitalName { get; set; }
public string ShortName { get; set; }
public string AreaCode { get; set; }
public int HospitalLevel { get; set; }
public int HospitalType { get; set; }
public int States { get; set; }
}
}
using System;
namespace Performance.EntityModels
{
public class Sys_User
{
public int ID { get; set; }
public string RealName { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Mail { get; set; }
public string Mobile { get; set; }
public int States { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
namespace Performance.Infrastructure
{
public class EnumItem
{
public string Name { get; set; }
public int Value { get; set; }
public string Description { get; set; }
}
/// <summary>
/// 枚举类型操作公共类。
/// </summary>
public static class EnumHelper
{
/// <summary>
/// 获取枚举所有成员名称。
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
public static string[] GetNames<T>()
{
return Enum.GetNames(typeof(T));
}
/// <summary>
/// 返回指定枚举类型的指定值的描述。
/// </summary>
/// <param name="t">枚举类型</param>
/// <param name="v">枚举值</param>
/// <returns></returns>
public static string GetDescription(Enum value)
{
try
{
Type type = value.GetType();
FieldInfo field = type.GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : string.Empty;
}
catch
{
return string.Empty;
}
}
/// <summary>
/// 获取疾病或药品的Type和Value
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static List<EnumItem> GetItems<T>()
{
var result = new List<EnumItem>();
Type t = typeof(T);
Array arrays = Enum.GetValues(t);
for (int i = 0; i < arrays.LongLength; i++)
{
object item = arrays.GetValue(i);
FieldInfo fieldInfo = item.GetType().GetField(item.ToString());
object[] attribArray = fieldInfo.GetCustomAttributes(false);
if (attribArray == null || attribArray.Length == 0)
{
result.Add(new EnumItem { Name = item.ToString(), Value = Convert.ToInt32(item), Description = item.ToString() });
}
else
{
DescriptionAttribute attrib = (DescriptionAttribute)attribArray[0];
result.Add(new EnumItem { Name = item.ToString(), Value = Convert.ToInt32(item), Description = attrib.Description });
}
}
return result;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Infrastructure
{
public static partial class UtilExtensions
{
public static string RemoveLineBreak(this string text)
{
return text.Replace("\n", "");
}
public static string RemoveEnter(this string text)
{
return text.Replace("\r", "");
}
}
}
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Infrastructure
{
public class LowercaseContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
public class IsoDateTimeConverterContent : IsoDateTimeConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTime)
{
DateTime dateTime = (DateTime)value;
if (dateTime == default(DateTime)
|| dateTime == DateTime.MinValue
|| dateTime.ToString("yyyy-MM-dd") == "1970-01-01"
|| dateTime.ToString("yyyy-MM-dd") == "1900-01-01")
{
writer.WriteValue("");
return;
}
}
base.WriteJson(writer, value, serializer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return base.ReadJson(reader, objectType, existingValue, serializer);
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Performance.Infrastructure
{
public static class ReflectionHelper
{
/// <summary>
/// 获取实现了接口的所有实例
/// </summary>
/// <typeparam name="TInterface">接口类型</typeparam>
/// <param name="assembly">在该程序集中查找</param>
public static List<TInterface> GetInstances<TInterface>(Assembly assembly)
{
var typeInterface = typeof(TInterface);
return assembly.GetTypes()
.Where(t => typeInterface.GetTypeInfo().IsAssignableFrom(t) && t != typeInterface && t.GetTypeInfo().IsAbstract == false)
.Select(t => (TInterface)Activator.CreateInstance(t)).ToList();
}
/// <summary>
/// 获取实现了接口的类型
/// </summary>
/// <typeparam name="TInterface">接口类型</typeparam>
/// <param name="assembly">在该程序集中查找</param>
public static List<Type> GetClassType<TInterface>(Assembly assembly)
{
var typeInterface = typeof(TInterface);
return assembly.GetTypes()
.Where(t => typeInterface.GetTypeInfo().IsAssignableFrom(t) && t != typeInterface && t.GetTypeInfo().IsAbstract == false).ToList(); ;
}
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Performance.Repository
{
public abstract class BaseRepository<TEntity>
where TEntity : class, new()
{
private DbContext context;
public BaseRepository(DbContext context)
{
this.context = context;
}
public bool Add(TEntity entity)
{
context.Set<TEntity>().Add(entity);
return context.SaveChanges() > 0;
}
public async Task<bool> AddAsync(TEntity entity)
{
await context.Set<TEntity>().AddAsync(entity);
return await context.SaveChangesAsync() > 0;
}
public bool AddRange(params TEntity[] entities)
{
context.Set<TEntity>().AddRange(entities);
return context.SaveChanges() > 0;
}
public async Task<bool> AddRangeAsync(params TEntity[] entities)
{
await context.Set<TEntity>().AddRangeAsync(entities);
return await context.SaveChangesAsync() > 0;
}
public async Task<bool> Delete(TEntity entity)
{
context.Set<TEntity>().Remove(entity);
return await context.SaveChangesAsync() > 0;
}
public async Task<bool> Update(TEntity entity)
{
context.Set<TEntity>().Update(entity);
return await context.SaveChangesAsync() > 0;
}
public IEnumerable<TEntity> GetEntities()
{
return context.Set<TEntity>();
}
public IEnumerable<TEntity> GetEntities(Expression<Func<TEntity, bool>> exp)
{
return CompileQuery(exp);
}
public IEnumerable<TEntity> GetEntitiesForPaging(int Page, int pageSize, Expression<Func<TEntity, bool>> exp)
{
return CompileQuery(exp).Skip((Page - 1) * pageSize).Take(pageSize);
}
public TEntity GetEntity(Expression<Func<TEntity, bool>> exp)
{
return CompileQuerySingle(exp);
}
private IEnumerable<TEntity> CompileQuery(Expression<Func<TEntity, bool>> exp)
{
var func = EF.CompileQuery((DbContext context, Expression<Func<TEntity, bool>> exps) => context.Set<TEntity>().Where(exp));
return func(context, exp);
}
private TEntity CompileQuerySingle(Expression<Func<TEntity, bool>> exp)
{
var func = EF.CompileQuery((DbContext context, Expression<Func<TEntity, bool>> exps) => context.Set<TEntity>().FirstOrDefault(exp));
return func(context, exp);
}
}
}
using Microsoft.EntityFrameworkCore;
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Repository
{
public class PerforRepository<TEntity> : BaseRepository<TEntity> where TEntity : class, new()
{
public PerforRepository(PerformanceDbContext context) : base(context)
{
}
}
}
using Performance.EntityModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Repository
{
public class PerforUserRepository : PerforRepository<Sys_User>
{
public PerforUserRepository(PerformanceDbContext context) : base(context)
{
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.0" />
<PackageReference Include="MySql.Data" Version="8.0.15" />
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.15" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.EntityModels\Performance.EntityModels.csproj" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Services
{
public interface IAutoInjection
{
}
}
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.IO;
namespace Performance.Services
{
public class PerExcelService : IAutoInjection
{
private PerSheetService _service;
public PerExcelService(PerSheetService service)
{
_service = service;
}
public PerExcel Analyze(string path)
{
PerExcel excel = new PerExcel
{
Path = path,
FileName = FileHelper.GetFileNameNoExtension(path),
Version = FileHelper.GetExtension(path) == ".xlsx" ? ExcelVersion.xlsx : ExcelVersion.xls,
PerSheet = new List<PerSheet>()
};
using (FileStream fs = new FileStream(path, FileMode.Open))
{
IWorkbook workbook = (excel.Version == ExcelVersion.xlsx)
? (IWorkbook)(new XSSFWorkbook(fs))
: (IWorkbook)(new HSSFWorkbook(fs));
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
var sheet = workbook.GetSheetAt(i);
var st = _service.Sheet(sheet);
excel.PerSheet.Add(st);
}
return excel;
}
}
}
}
using NPOI.SS.UserModel;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Performance.Services
{
public class PerHeaderService : IAutoInjection
{
/// <summary>
/// excel列头转换为矩阵
/// </summary>
/// <param name="sheet"></param>
/// <param name="point"></param>
/// <returns></returns>
private List<List<int>> ConvertToMatrix(ISheet sheet, PerSheetPoint point)
{
point.HeaderFirstRowNum = point.HeaderFirstRowNum.HasValue ? point.HeaderFirstRowNum : sheet.FirstRowNum;
point.HeaderLastRowNum = point.HeaderLastRowNum.HasValue ? point.HeaderLastRowNum : sheet.LastRowNum;
List<List<int>> matrix = new List<List<int>>();
for (int r = point.HeaderFirstRowNum.Value; r < point.HeaderLastRowNum + 1; r++)
{
List<int> cell = new List<int>();
var row = sheet.GetRow(r);
point.HeaderFirstCellNum = point.HeaderFirstCellNum.HasValue ? point.HeaderFirstCellNum : row.FirstCellNum;
for (int c = point.HeaderFirstCellNum.Value; c < row.LastCellNum; c++)
{
cell.Add(string.IsNullOrEmpty(row.GetCell(c)?.ToString()) ? 0 : 1);
}
matrix.Add(cell);
}
return matrix;
}
/// <summary>
/// 递归 获得具有层级关系的列头
/// </summary>
/// <param name="cells"></param>
/// <param name="parentCell"></param>
/// <param name="pointRow"></param>
/// <param name="level"></param>
/// <returns></returns>
private List<PerHeader> RecursionFill(List<PerHeader> cells, PerHeader parentCell, int pointRow, int level)
{
if (cells == null || !cells.Any())
return null;
List<PerHeader> sheetHeaders = new List<PerHeader>();
var groupData = cells.GroupBy(t => t.PointRow);
//获取起始行号
if (pointRow <= 0)
{
pointRow = groupData.Min(t => t.Key);
level = 0;
}
IEnumerable<PerHeader> child = cells.Where(t => t.PointRow == pointRow);
//根据合并列的坐标及合并单元格数量,查找子集列头
if (parentCell != null)
child = child.Where(t => t.PointCell >= parentCell.PointCell && (t.PointCell + t.MergeCell - 1) <= (parentCell.PointCell + parentCell.MergeCell - 1));
foreach (var headerCell in child)
{
headerCell.Level = level;
headerCell.Parent = parentCell;
if (groupData.Any(t => t.Key > pointRow))
{
int nextpoint = groupData.Where(t => t.Key > pointRow).Min(t => t.Key);
headerCell.Children = RecursionFill(cells, headerCell, nextpoint, level + 1);
}
sheetHeaders.Add(headerCell);
}
return sheetHeaders;
}
/// <summary>
/// 读取excel列头
/// </summary>
/// <param name="sheet"></param>
/// <param name="point"></param>
/// <returns></returns>
public List<PerHeader> GetPerHeader(ISheet sheet, PerSheetPoint point)
{
List<List<int>> matrix = ConvertToMatrix(sheet, point);
var sheetHeaders = ReadHeadMatrix(sheet, point, matrix);
var result = RecursionFill(sheetHeaders, null, 0, 0);
return result;
}
/// <summary>
/// 读取excel层级最低列头
/// </summary>
/// <param name="sheet"></param>
/// <param name="point"></param>
/// <returns></returns>
public List<PerHeader> GetPerHeaderReverse(ISheet sheet, PerSheetPoint point)
{
var sheetHeaders = GetPerHeader(sheet, point);
if (sheetHeaders == null || !sheetHeaders.Any())
return null;
return LastLevel(sheetHeaders);
}
/// <summary>
/// 递归 找出层级最低列头
/// </summary>
/// <param name="sheetHeaders"></param>
/// <returns></returns>
private List<PerHeader> LastLevel(List<PerHeader> sheetHeaders)
{
if (sheetHeaders == null || !sheetHeaders.Any())
return null;
var headList = new List<PerHeader>();
foreach (var cell in sheetHeaders)
{
if (cell.IsHasChildren)
{
headList.AddRange(LastLevel(cell.Children));
}
else
{
headList.Add(cell);
}
}
return headList;
}
/// <summary>
/// 读取excel列头
/// </summary>
/// <param name="sheet"></param>
/// <param name="point"></param>
/// <returns></returns>
private List<PerHeader> ReadHeadMatrix(ISheet sheet, PerSheetPoint point, List<List<int>> matrix)
{
List<PerHeader> headerList = new List<PerHeader>();
for (int r = 0; r < matrix.Count; r++)
{
for (int c = 0; c < matrix[r].Count; c++)
{
int ri = 1, ci = 1;
if (matrix[r][c] == 1)
{
for (int i = r + 1; i < matrix.Count; i++)
{
if (matrix[i][c] == 1 || matrix[i][c] == -1)
break;
//var num = matrix[i][c];
matrix[i][c] = -1;
ri++;
}
for (int i = c + 1; i < matrix[r].Count; i++)
{
if (matrix[r][i] == 1 || matrix[r][i] == -1)
break;
//var num = matrix[r][i];
matrix[r][i] = -1;
ci++;
}
var header = new PerHeader
{
PointRow = point.HeaderFirstRowNum.Value + r,
PointCell = point.HeaderFirstCellNum.Value + c,
MergeCell = ci,
MergeRow = ri,
CellName = sheet.GetRow(point.HeaderFirstRowNum.Value + r)
?.GetCell(point.HeaderFirstCellNum.Value + c)
?.ToString()
?.RemoveLineBreak()
};
headerList.Add(header);
}
}
}
return headerList;
}
}
}
using NPOI.SS.UserModel;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Performance.Services
{
public class PerSheetService : IAutoInjection
{
public PerSheet Sheet(ISheet sheet)
{
PerSheet perSheet = new PerSheet();
perSheet.SheetName = sheet.SheetName;
perSheet.SheetType = GetSheetType(sheet.SheetName);
perSheet.ModuleName = EnumHelper.GetDescription(perSheet.SheetType);
IPerSheetDataRead sheetRead = PerSheetDataFactory.GetAnalyze(perSheet.SheetType);
perSheet.PerData = AnalyzeData(sheet , sheetRead);
return perSheet;
}
public SheetType GetSheetType(string sheetName)
{
if (sheetName.StartsWith("工作量"))
{
return SheetType.Expend;
}
else if (sheetName.StartsWith("生成成本"))
{
return SheetType.Workload;
}
return SheetType.Unidentifiable;
}
public List<PerData> AnalyzeData(ISheet sheet, IPerSheetDataRead sheetRead)
{
List<PerData> dataList = new List<PerData>();
PerHeaderService perHeader = new PerHeaderService();
var headList = perHeader.GetPerHeaderReverse(sheet, sheetRead.Point);
var vhead = headList.Where(t => t.PointCell != sheetRead.Point.StandardCellNum && t.PointCell != sheetRead.Point.DeptCellNum)
.OrderBy(t => t.PointCell);
for (int r = sheetRead.Point.DataFirstRowNum.Value; r < sheet.LastRowNum + 1; r++)
{
var row = sheet.GetRow(r);
for (int c = 0; c < vhead.Count(); c++)
{
PerData data = sheetRead.GetPerData(row, vhead.ElementAt(c));
dataList.Add(data);
}
}
return dataList;
}
}
}
using NPOI.SS.UserModel;
using Performance.DtoModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Services
{
public interface IPerSheetDataRead
{
PerSheetPoint Point { get; }
PerData GetPerData(IRow row, PerHeader perHeader);
}
}
using Performance.DtoModels;
using System;
using System.Collections.Generic;
using System.Text;
namespace Performance.Services
{
public class PerSheetDataFactory
{
public static IPerSheetDataRead GetAnalyze(SheetType sheetType)
{
IPerSheetDataRead analyze = null;
switch (sheetType)
{
case SheetType.Employee:
break;
case SheetType.Income:
break;
case SheetType.Expend:
analyze = new PerSheetDataReadExpend();
break;
case SheetType.Overtime:
break;
case SheetType.Workload:
analyze = new PerSheetDataReadWorkload();
break;
default:
break;
}
return analyze;
}
}
}
using NPOI.SS.UserModel;
using Performance.DtoModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Performance.Services
{
public class PerSheetDataReadExpend : IPerSheetDataRead
{
public PerSheetPoint Point => new PerSheetPoint
{
HeaderFirstRowNum = 3,
HeaderLastRowNum = 4,
HeaderFirstCellNum = 3,
DataFirstRowNum = 6,
FactorRow = 5,
StandardCellNum = 3,
DeptCellNum = 4
};
public PerData GetPerData(IRow row, PerHeader perHeader)
{
return new PerDataExpend
{
StandardName = row.GetCell(Point.StandardCellNum.Value).ToString(),
Department = row.GetCell(Point.DeptCellNum.Value).ToString(),
ParentType = perHeader.Parent?.CellName,
TypeName = perHeader.CellName,
CellValue = Convert.ToDecimal(row.GetCell(perHeader.PointCell).ToString()),
Annotation = row.GetCell(perHeader.PointCell).CellComment?.String.String,
};
}
}
}
using NPOI.SS.UserModel;
using Performance.DtoModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Performance.Services
{
public class PerSheetDataReadWorkload : IPerSheetDataRead
{
public PerSheetPoint Point => new PerSheetPoint
{
HeaderFirstRowNum = 1,
HeaderLastRowNum = 2,
HeaderFirstCellNum = 1,
DataFirstRowNum = 3,
StandardCellNum = 1,
DeptCellNum = 2
};
public PerData GetPerData(IRow row, PerHeader perHeader)
{
return new PerDataWorkload
{
StandardName = row.GetCell(Point.StandardCellNum.Value).ToString(),
Department = row.GetCell(Point.DeptCellNum.Value).ToString(),
ParentType = perHeader.Parent?.CellName,
TypeName = perHeader.CellName,
CellValue = Convert.ToDecimal(row.GetCell(perHeader.PointCell).ToString()),
Annotation = row.GetCell(perHeader.PointCell).CellComment?.String.String,
};
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DotNetCore.NPOI" Version="1.2.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Performance.DtoModels\Performance.DtoModels.csproj" />
<ProjectReference Include="..\Performance.EntityModels\Performance.EntityModels.csproj" />
<ProjectReference Include="..\Performance.Infrastructure\Performance.Infrastructure.csproj" />
<ProjectReference Include="..\Performance.Repository\Performance.Repository.csproj" />
</ItemGroup>
</Project>
using Microsoft.Extensions.DependencyInjection;
using Performance.Infrastructure;
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Performance.Services
{
public static class PerformanceServiceExtensions
{
public static IServiceCollection AddPerformanceService(this IServiceCollection services)
{
var types = ReflectionHelper.GetClassType<IAutoInjection>(Assembly.GetExecutingAssembly());
foreach (var type in types)
{
services.AddScoped(type);
}
var repository = typeof(PerforRepository<>).Assembly.GetTypes().Where(t => t.IsClass && !t.IsAbstract);
foreach (var type in repository)
{
services.AddScoped(type);
}
return services;
}
}
}
using Performance.EntityModels;
using Performance.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Performance.Services
{
public class UserService : IAutoInjection
{
PerforRepository<Sys_User> _userRepository;
public UserService(PerforRepository<Sys_User> userRepository)
{
this._userRepository = userRepository;
}
public List<Sys_User> GetUser()
{
return _userRepository.GetEntities().ToList();
}
}
}

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2026
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Performance.ConsoleApp", "Performance.ConsoleApp\Performance.ConsoleApp.csproj", "{59218B05-5CE3-4EC1-A304-28183F191A04}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Performance.Services", "Performance.Services\Performance.Services.csproj", "{930CBA1F-A51A-4A12-897A-AA6ED02D3E70}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Performance.Infrastructure", "Performance.Infrastructure\Performance.Infrastructure.csproj", "{5E91CFB3-D240-4E38-9E3E-398D53621387}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1.site", "1.site", "{69CFD3FA-0B61-41D4-A9E8-44B933001293}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2.services", "2.services", "{2E5D3959-48C9-4BAD-89BF-9CF1DDCB453D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3.repository", "3.repository", "{95E7A23D-DC0E-4C27-AD7C-EAF4917012EF}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "4.infrastructure", "4.infrastructure", "{B132BEEE-14FF-4DDE-B8D6-7C66AD2B3433}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Performance.Repository", "Performance.Repository\Performance.Repository.csproj", "{9F7723A3-B6BE-4690-BC56-FF93D9992621}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Performance.DtoModels", "Performance.DtoModels\Performance.DtoModels.csproj", "{76531E3A-4BCD-4C20-A14C-5D6CCA1C9AEF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Performance.EntityModels", "Performance.EntityModels\Performance.EntityModels.csproj", "{F7708C0C-0B0B-4E7E-A995-E39F7044FD11}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Performance.Api", "Performance.Api\Performance.Api.csproj", "{3AE00FF5-F0BA-4D72-A23B-770186309327}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{59218B05-5CE3-4EC1-A304-28183F191A04}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{59218B05-5CE3-4EC1-A304-28183F191A04}.Debug|Any CPU.Build.0 = Debug|Any CPU
{59218B05-5CE3-4EC1-A304-28183F191A04}.Release|Any CPU.ActiveCfg = Release|Any CPU
{59218B05-5CE3-4EC1-A304-28183F191A04}.Release|Any CPU.Build.0 = Release|Any CPU
{930CBA1F-A51A-4A12-897A-AA6ED02D3E70}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{930CBA1F-A51A-4A12-897A-AA6ED02D3E70}.Debug|Any CPU.Build.0 = Debug|Any CPU
{930CBA1F-A51A-4A12-897A-AA6ED02D3E70}.Release|Any CPU.ActiveCfg = Release|Any CPU
{930CBA1F-A51A-4A12-897A-AA6ED02D3E70}.Release|Any CPU.Build.0 = Release|Any CPU
{5E91CFB3-D240-4E38-9E3E-398D53621387}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5E91CFB3-D240-4E38-9E3E-398D53621387}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5E91CFB3-D240-4E38-9E3E-398D53621387}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5E91CFB3-D240-4E38-9E3E-398D53621387}.Release|Any CPU.Build.0 = Release|Any CPU
{9F7723A3-B6BE-4690-BC56-FF93D9992621}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9F7723A3-B6BE-4690-BC56-FF93D9992621}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9F7723A3-B6BE-4690-BC56-FF93D9992621}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9F7723A3-B6BE-4690-BC56-FF93D9992621}.Release|Any CPU.Build.0 = Release|Any CPU
{76531E3A-4BCD-4C20-A14C-5D6CCA1C9AEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{76531E3A-4BCD-4C20-A14C-5D6CCA1C9AEF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{76531E3A-4BCD-4C20-A14C-5D6CCA1C9AEF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{76531E3A-4BCD-4C20-A14C-5D6CCA1C9AEF}.Release|Any CPU.Build.0 = Release|Any CPU
{F7708C0C-0B0B-4E7E-A995-E39F7044FD11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F7708C0C-0B0B-4E7E-A995-E39F7044FD11}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F7708C0C-0B0B-4E7E-A995-E39F7044FD11}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F7708C0C-0B0B-4E7E-A995-E39F7044FD11}.Release|Any CPU.Build.0 = Release|Any CPU
{3AE00FF5-F0BA-4D72-A23B-770186309327}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3AE00FF5-F0BA-4D72-A23B-770186309327}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3AE00FF5-F0BA-4D72-A23B-770186309327}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3AE00FF5-F0BA-4D72-A23B-770186309327}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{59218B05-5CE3-4EC1-A304-28183F191A04} = {69CFD3FA-0B61-41D4-A9E8-44B933001293}
{930CBA1F-A51A-4A12-897A-AA6ED02D3E70} = {2E5D3959-48C9-4BAD-89BF-9CF1DDCB453D}
{5E91CFB3-D240-4E38-9E3E-398D53621387} = {B132BEEE-14FF-4DDE-B8D6-7C66AD2B3433}
{9F7723A3-B6BE-4690-BC56-FF93D9992621} = {95E7A23D-DC0E-4C27-AD7C-EAF4917012EF}
{76531E3A-4BCD-4C20-A14C-5D6CCA1C9AEF} = {2E5D3959-48C9-4BAD-89BF-9CF1DDCB453D}
{F7708C0C-0B0B-4E7E-A995-E39F7044FD11} = {95E7A23D-DC0E-4C27-AD7C-EAF4917012EF}
{3AE00FF5-F0BA-4D72-A23B-770186309327} = {69CFD3FA-0B61-41D4-A9E8-44B933001293}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {610FC42C-1DE1-4925-93DD-F02908B9FF47}
EndGlobalSection
EndGlobal
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment