/// <summary> /// Adds LiteX SQLite Cache manager services /// </summary> /// <param name="services"></param> /// <param name="config">SQLite configuration settings, default: use 'SQLiteConfig' from appsettings.json</param> /// <returns></returns> public static IServiceCollection AddLiteXSQLiteCache(this IServiceCollection services, SQLiteConfig config = null) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (config == null) { IConfiguration requiredService = ServiceProviderServiceExtensions.GetRequiredService <IConfiguration>((IServiceProvider)ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services)); IConfigurationSection section = requiredService.GetSection(SQLiteCacheDefaults.SettingsSection); config = ((section != null) ? ConfigurationBinder.Get <SQLiteConfig>(section) : null); if (config == null) { config = new SQLiteConfig { FileName = SQLiteCacheDefaults.FileName, FilePath = SQLiteCacheDefaults.FilePath, OpenMode = 0, CacheMode = 0, EnableLogging = LiteXCacheDefaults.EnableLogging }; } config.FilePath = ((!string.IsNullOrWhiteSpace(config.FilePath)) ? config.FilePath : SQLiteCacheDefaults.FilePath); } return(services.AddLiteXSQLiteCache(delegate(SQLiteConfig option) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) option.FileName = config.FileName; option.FilePath = config.FilePath; option.OpenMode = config.OpenMode; option.CacheMode = config.CacheMode; })); }
private static IServiceCollection AddSwaggerInternal( this IServiceCollection services, string applicationName, Action <SwaggerGenOptions> configure = null) { services.AddApiVersioning((Action <ApiVersioningOptions>)(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); })); services.AddVersionedApiExplorer((Action <ApiExplorerOptions>)(options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; })); services.AddSwaggerGen((Action <SwaggerGenOptions>)(options => { foreach (ApiVersionDescription versionDescription in ServiceProviderServiceExtensions .GetRequiredService <IApiVersionDescriptionProvider>( ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services)) .ApiVersionDescriptions) { options.SwaggerDoc(versionDescription.GroupName, new OpenApiInfo() { Title = applicationName, Version = versionDescription.ApiVersion.ToString() }); } options.UseInlineDefinitionsForEnums(); options.MapType <Guid>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "string", Format = "uuid" })); options.MapType <Decimal>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "number", Format = "" })); options.MapType <Decimal?>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "number", Format = "" })); Action <SwaggerGenOptions> action = configure; if (action == null) { return; } action(options); })); return(services); }
/// <summary> /// Called from <see cref="M:Microsoft.AspNetCore.Mvc.RequireHttpsAttribute.OnAuthorization(Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)" /> if the request is not received over HTTPS. Expectation is /// <see cref="P:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result" /> will not be <c>null</c> after this method returns. /// </summary> /// <param name="filterContext">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext" /> to update.</param> /// <remarks> /// If it was a GET request, default implementation sets <see cref="P:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result" /> to a /// result which will redirect the client to the HTTPS version of the request URI. Otherwise, default /// implementation sets <see cref="P:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext.Result" /> to a result which will set the status /// code to <c>403</c> (Forbidden). /// </remarks> protected virtual void HandleRequest(AuthorizationFilterContext filterContext) { if (!string.Equals(filterContext.HttpContext.Request.Method, "GET", StringComparison.OrdinalIgnoreCase)) { filterContext.Result = (new StatusCodeResult(403)); } else { HttpRequest request = filterContext.HttpContext.Request; HostString host = default(HostString);// request.Host; string hostString = this.Host; IOptions <MvcOptions> requiredService = ServiceProviderServiceExtensions.GetRequiredService <IOptions <MvcOptions> >(filterContext.HttpContext.RequestServices); if (requiredService.Value.SslPort.HasValue && requiredService.Value.SslPort > 0) { host = new HostString(hostString, requiredService.Value.SslPort.Value); } else { host = new HostString(hostString); } bool permanent = _permanent ?? requiredService.Value.RequireHttpsPermanent; string[] obj = new string[5] { "https://", host.ToUriComponent(), request.PathBase.ToUriComponent(), request.Path.ToUriComponent(), request.QueryString.ToUriComponent() }; string url = string.Concat(obj); filterContext.Result = (new RedirectResult(url, permanent)); } }
public static IApplicationBuilder UsePoweredBy(this IApplicationBuilder app, bool enabled, string headerValue) { stackVariable2 = ServiceProviderServiceExtensions.GetRequiredService <IPoweredByMiddlewareOptions>(app.get_ApplicationServices()); stackVariable2.set_Enabled(enabled); stackVariable2.set_HeaderValue(headerValue); return(app); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { //app.UseDeveloperExceptionPage(); app.UseExceptionHandler("/Error"); } else { app.UseExceptionHandler("/Error"); } var provider = new FileExtensionContentTypeProvider(); provider.Mappings[".jsp"] = "text/html"; app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider }); app.UseCookiePolicy(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); GTXMethod.config = Configuration; GTXMethod.set = ServiceProviderServiceExtensions.GetRequiredService <YsbqcSetting>(app.ApplicationServices); }
public static IServiceCollection AddSingletonFactory <T, TFactory>(this IServiceCollection collection) where T : class where TFactory : class, IServiceFactory <T> { collection.AddTransient <TFactory>(); return(AddInternal <T, TFactory>(collection, p => ServiceProviderServiceExtensions.GetRequiredService <TFactory>(p), ServiceLifetime.Singleton)); }
public Task Execute(IJobExecutionContext context) { ILogger logger = ServiceProviderServiceExtensions.GetRequiredService <ILogger <DemoJob> >( ServiceProviderExtension.ServiceProvider); logger.LogInformation(string.Format("{0}执行一次", DateTime.Now)); return(Task.CompletedTask); }
public static IUniversalBuilder AddRequiredPlatformServices(this IUniversalBuilder builder) { Check.NotNull(builder); builder.Services.AddOptions(); builder.Services.TryAddSingleton(provider => ServiceProviderServiceExtensions.GetRequiredService <IOptions <UniversalOption> >(provider).Value); return(builder); }
public async Task <IValueProvider> BindAsync(BindingContext context) { await Task.Yield(); var scope = InjectBindingProvider.Scopes.GetOrAdd(context.FunctionInstanceId, (_) => ServiceProviderServiceExtensions.CreateScope(_serviceProvider)); var value = ServiceProviderServiceExtensions.GetRequiredService(scope.ServiceProvider, _type); return(await BindAsync(value, context.ValueContext)); }
public async Task Print() { ServiceCollection services = new(); services.AddSingleton <ILoggerFactory>(_ => NullLoggerFactory.Instance); new Startup().ConfigureServices(services); await using var provider = services.BuildServiceProvider(); var schema = ServiceProviderServiceExtensions.GetRequiredService <ISchema>(provider); SchemaPrinter printer = new(schema); var print = printer.Print(); await Verifier.Verify(print); }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (!context.ActionDescriptor.EndpointMetadata.Any(item => item is AllowNotConfirmed || item is AllowAnonymousFilter || item is IAllowAnonymous)) { if (!context.HttpContext.User.Identity.IsAuthenticated) { context.Result = new ForbidResult(); return; } try { var confirmed = context.HttpContext.User.HasClaim(CustomClaimTypes.AccountConfirmed, true.ToString()); //Make a call to database to ensure Consistency if (!confirmed) { BuildTrackerContext dbContext = ServiceProviderServiceExtensions.GetRequiredService <BuildTrackerContext>(context.HttpContext.RequestServices); var id = int.Parse(context.HttpContext.User.Identity?.Name); var user = await dbContext.FindAsync <User>(id); if (user == null) { context.Result = new UnauthorizedResult(); return; } else if (!user.AccountConfirmed) { var dic = new Dictionary <string, string> { { "Reason", "Account not Confirmed" }, { "AuthUrl", "api/users/confirm/" + user.Id } }; AuthenticationProperties props = new AuthenticationProperties(dic); var result = JsonConvert.SerializeObject(new { error = "Account not confirmed" }); await context.HttpContext.Response.WriteAsync(result); context.Result = new ForbidResult(props); return; } } } catch { context.Result = new ForbidResult(); return; } } }
public static void EnsurePopulated(IApplicationBuilder app) { AirportContext context = ServiceProviderServiceExtensions.GetRequiredService <AirportContext>(app.ApplicationServices); context.Database.EnsureCreated(); if (!context.Tickets.Any()) { context.Tickets.AddRange( new Ticket() { Id = 1, Price = 1M, FlightNumber = "", }, new Ticket() { Id = 2, Price = 1M, FlightNumber = "", } ); context.SaveChanges(); } if (!context.PlaneTypes.Any()) { context.PlaneTypes.AddRange( new PlaneType() { Id = 1, Model = "AN", Seats = 100, }, new PlaneType() { Id = 2, Model = "AN", Seats = 200, } ); context.SaveChanges(); } }
public override void OnApplicationInitialization(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); var env = ServiceProviderServiceExtensions.GetRequiredService <IWebHostEnvironment>(context.ServiceProvider); NLog.LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger(); NLog.LogManager.Configuration.Variables["connectionString"] = context.Configuration["ConnectionStrings:MySql"]; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //避免日志中的中文输出乱码 // 环境变量,开发环境 if (env.IsDevelopment()) { // 生成异常页面 app.UseDeveloperExceptionPage(); } // 使用HSTS的中间件,该中间件添加了严格传输安全头 app.UseHsts(); // 转发将标头代理到当前请求,配合 Nginx 使用,获取用户真实IP app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); // 跨域 app.UseCors(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); // 异常处理中间件 //app.UseMiddleware<ExceptionHandlerMiddleware>(); app.UseSwaggerMiddle(); // HTTP => HTTPS app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); // 路由映射 app.UseEndpoints(endpoints => { //全局路由配置 endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}" ); }); }
public static IApplicationBuilder UseOrchardCore(this IApplicationBuilder app, Action <IApplicationBuilder> configure = null) { V_0 = ServiceProviderServiceExtensions.GetRequiredService <IHostEnvironment>(app.get_ApplicationServices()); V_1 = ServiceProviderServiceExtensions.GetRequiredService <IApplicationContext>(app.get_ApplicationServices()); stackVariable8 = new IFileProvider[2]; stackVariable8[0] = new ModuleEmbeddedFileProvider(V_1); stackVariable8[1] = V_0.get_ContentRootFileProvider(); V_0.set_ContentRootFileProvider(new CompositeFileProvider(stackVariable8)); ServiceProviderServiceExtensions.GetRequiredService <IWebHostEnvironment>(app.get_ApplicationServices()).set_ContentRootFileProvider(V_0.get_ContentRootFileProvider()); dummyVar0 = UseMiddlewareExtensions.UseMiddleware <PoweredByMiddleware>(app, Array.Empty <object>()); dummyVar1 = UseMiddlewareExtensions.UseMiddleware <ModularTenantContainerMiddleware>(app, Array.Empty <object>()); if (configure != null) { configure.Invoke(app); } stackVariable30 = new object[1]; stackVariable30[0] = app.get_ServerFeatures(); dummyVar2 = UseMiddlewareExtensions.UseMiddleware <ModularTenantRouterMiddleware>(app, stackVariable30); return(app); }
private static ODataRoute MapDynamicODataServiceRoute(this IRouteBuilder builder, string routeName, string routePrefix, IODataPathHandler pathHandler, IEnumerable <IODataRoutingConvention> routingConventions, IDataSource dataSource) { ServiceProviderServiceExtensions.GetRequiredService <ApplicationPartManager>(builder.ServiceProvider).ApplicationParts.Add(new AssemblyPart(typeof(DynamicODataController).Assembly)); var odataRoute = builder.MapODataServiceRoute(routeName, routePrefix, containerBuilder => { containerBuilder .AddService <IEdmModel>(Microsoft.OData.ServiceLifetime.Singleton, sp => dataSource.Model) .AddService <IDataSource>(Microsoft.OData.ServiceLifetime.Scoped, sp => dataSource) .AddService(Microsoft.OData.ServiceLifetime.Scoped, sp => routingConventions.ToList().AsEnumerable()); if (pathHandler != null) { containerBuilder.AddService(Microsoft.OData.ServiceLifetime.Singleton, sp => pathHandler); } }); return(odataRoute); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, YsbqcSetting set) { //var rewrite = new RewriteOptions().AddRedirect(@"m2/(\w+)", "?m3=$1"); //app.UseRewriter(rewrite); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } //MyRewrite(app); var provider = new FileExtensionContentTypeProvider(); provider.Mappings[".jsp"] = "text/html"; app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider }); app.UseCookiePolicy(); app.UseSession(); app.UseMiddleware <SessionMiddleware>(set); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); GTXMethod.config = Configuration; GTXMethod.set = ServiceProviderServiceExtensions.GetRequiredService <YsbqcSetting>(app.ApplicationServices); }
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { if (Policy != null || (object)PolicyProvider != null) { return(this); } IAuthorizationPolicyProvider requiredService = ServiceProviderServiceExtensions.GetRequiredService <IAuthorizationPolicyProvider>(serviceProvider); if (PolicyProvider == null) { PolicyProvider = ServiceProviderServiceExtensions.GetRequiredService <IAuthorizationPolicyProvider>(serviceProvider); } if (Policy == null) { Policy = AuthorizationPolicy.CombineAsync(requiredService, AuthorizeData).GetAwaiter().GetResult(); } if (AuthorizeFilter == null) { AuthorizeFilter = ServiceProviderServiceExtensions.GetService <IAuthorizeFilter>(serviceProvider); } return(this); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); Console.WriteLine("Environment:" + env.EnvironmentName); Configuration = builder.Build(); var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope(); var context = ServiceProviderServiceExtensions.GetRequiredService <Context>(serviceScope.ServiceProvider); context.Database.Migrate(); context.Seed(); app.UseGraphQL <Schema>(); app.UseGraphQLPlayground(new GraphQLPlaygroundOptions { Path = "/ui/playground", HideTracingResponse = true, }); }
public static void EnsurePopulated(IApplicationBuilder app) { AirportContext context = ServiceProviderServiceExtensions.GetRequiredService <AirportContext>(app.ApplicationServices); context.Database.EnsureDeleted(); if (!context.Database.EnsureCreated()) { return; } context.Tickets.AddRange( new Ticket() { Price = 111M, FlightForeignKey = 1, }, new Ticket() { //Id = 2, Price = 200M, FlightForeignKey = 2, }, new Ticket() { //Id = 3, Price = 300M, FlightForeignKey = 3, } ); context.PlaneTypes.AddRange( new PlaneType() { //Id = 1, Model = "AN", Seats = 100, Payload = 3000 }, new PlaneType() { //Id = 2, Model = "AN", Seats = 200, Payload = 5000 }, new PlaneType() { //Id = 3, Model = "AN", Seats = 300, Payload = 10000 } ); context.Planes.AddRange( new Plane() { //Id = 1, Name = "Plane1", Type = 1, TimeUsed = "100000" }, new Plane() { //Id = 2, Name = "Plane2", Type = 2, TimeUsed = "20000" }, new Plane() { //Id = 3, Name = "Plane3", Type = 3, TimeUsed = "30000" } ); context.Pilots.AddRange( new Pilot() { //Id = 1, Name = "John", Surname = "Smith", BirthDay = "1982/05/23", Experience = 20000, }, new Pilot() { //Id = 2, Name = "Scott", Surname = "Jonson", BirthDay = "1992/12/03", Experience = 500, }, new Pilot() { //Id = 3, Name = "Pall", Surname = "Green", BirthDay = "1989/07/13", Experience = 7000, } ); context.Flightattendants.AddRange( new Flightattendant() { //Id = 1, Name = "Mary", Surname = "Smith", BirthDay = "1999/05/21", CrewForeignKey = 1 }, new Flightattendant() { //Id = 2, Name = "Jane", Surname = "Jonson", BirthDay = "1998/15/03", CrewForeignKey = 1 }, new Flightattendant() { //Id = 3, Name = "Liza", Surname = "Green", BirthDay = "1999/08/01", CrewForeignKey = 3 }, new Flightattendant() { //Id = 3, Name = "Liza", Surname = "Tomas", BirthDay = "1997/07/01", CrewForeignKey = 2 } ); context.Flights.AddRange( new Flight() { //Id = 1, Number = "QW543200", Departure = "Kyiv", Destination = "Lviv", DeparturingTime = "2018-12-14 10:13:20", ArrivingTime = "2018-12-14 10:43:20", Tickets = new List <Ticket>(), }, new Flight() { //Id = 3, Number = "PY987500", Departure = "Kyiv", Destination = "Barcelona", DeparturingTime = "2018-12-15 15:13:20", ArrivingTime = "2018-12-15 17:43:20", Tickets = new List <Ticket>(), }, new Flight() { //Id = 3, Number = "KJ457000", Departure = "Kyiv", Destination = "Toronto", DeparturingTime = "2018-10-15 05:13:20", ArrivingTime = "2018-10-15 23:43:20", Tickets = new List <Ticket>(), } ); context.Crews.AddRange( new Crew() { //Id = 1, Pilot = 1, FlightAttendantsList = new List <Flightattendant>(), }, new Crew() { //Id = 1, Pilot = 2, FlightAttendantsList = new List <Flightattendant>(), }, new Crew() { //Id = 1, Pilot = 3, FlightAttendantsList = new List <Flightattendant>(), } ); context.Departures.AddRange( new Departure() { //Id = 1, Flight = 1, Crew = 1, DepartingTime = "2018-12-14 10:33:20", Plane = 1, }, new Departure() { //Id = 1, Flight = 2, Crew = 2, DepartingTime = "2018-12-15 15:23:20", Plane = 2, }, new Departure() { //Id = 1, Flight = 3, Crew = 3, DepartingTime = "2018-10-15 05:18:20", Plane = 3, } ); context.SaveChanges(); }
public static IApplicationBuilder UsePoweredByOrchardCore(this IApplicationBuilder app, bool enabled) { ServiceProviderServiceExtensions.GetRequiredService <IPoweredByMiddlewareOptions>(app.get_ApplicationServices()).set_Enabled(enabled); return(app); }
private static IServiceCollection AddSwaggerInternal( this IServiceCollection services, string applicationName, Action <SwaggerGenOptions> configure = null) { services.AddApiVersioning((Action <ApiVersioningOptions>)(options => { options.ReportApiVersions = true; options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); })); services.AddVersionedApiExplorer((Action <ApiExplorerOptions>)(options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; })); services.AddSwaggerGen((Action <SwaggerGenOptions>)(options => { foreach (ApiVersionDescription versionDescription in (IEnumerable <ApiVersionDescription>)ServiceProviderServiceExtensions.GetRequiredService <IApiVersionDescriptionProvider>(ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services)).ApiVersionDescriptions) { options.SwaggerDoc(versionDescription.GroupName, new OpenApiInfo() { Title = applicationName, Version = versionDescription.ApiVersion.ToString() }); } options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty <string>() } }); options.UseInlineDefinitionsForEnums(); options.MapType <Guid>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "string", Format = "uuid" })); options.MapType <Decimal>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "number", Format = "" })); options.MapType <Decimal?>((Func <OpenApiSchema>)(() => new OpenApiSchema() { Type = "number", Format = "" })); Action <SwaggerGenOptions> action = configure; if (action == null) { return; } action(options); })); return(services); }
public MediaProvider() : base(ServiceProviderServiceExtensions.GetRequiredService <BaseFactory>(ServiceLocator.ServiceProvider)) { }
public void Test1() { IHostingEnvironment env = ServiceProviderExtension.ServiceProvider.GetRequiredService <IHostingEnvironment>(); ILogger logger = ServiceProviderServiceExtensions.GetRequiredService <ILogger <Test> >( ServiceProviderExtension.ServiceProvider); }
public static void ListToSheetXlsx <T>(XSSFWorkbook workbook, List <T> list, string sheetName) { XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(sheetName); XSSFCellStyle headStyle = workbook.GetHeadStyle(); //值类型直接返回第一列 Type tp = typeof(T); //属性列表 PropertyInfo[] properties = tp.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); //property.Name是属性的英文名,怎么转换成中文?使用DescriptionAttribute特性 List <string> fieldStringArray = new List <string>(); List <PropertyInfo> propertiesUsed = new List <PropertyInfo>(); foreach (var property in properties) { if (Attribute.IsDefined(property, typeof(DescriptionAttribute))) { fieldStringArray.Add(property.GetEnumDescription()); propertiesUsed.Add(property); } } int fieldCount = fieldStringArray.Count; XSSFRow headerRow = (XSSFRow)sheet.CreateRow(0); headerRow.HeightInPoints = 20; for (int i = 0; i < fieldCount; i++) { #region 表头及样式 headerRow.CreateCell(i).SetCellValue(fieldStringArray[i]); headerRow.GetCell(i).CellStyle = headStyle; sheet.AutoSizeColumn(i); #endregion } var count = list.Count(); #region 单元格样式 ICellStyle styleCell = workbook.CreateCellStyle(); styleCell.Alignment = HorizontalAlignment.Center; //居中 styleCell.VerticalAlignment = VerticalAlignment.Center; //垂直居中 #endregion for (int i = 0; i < count; i++) { XSSFRow dataRow = (XSSFRow)sheet.CreateRow(i + 1); var data = list[i]; for (int cellIndex = 0; cellIndex < fieldCount; cellIndex++) { XSSFCell newCell = (XSSFCell)dataRow.CreateCell(cellIndex, CellType.String); var property = propertiesUsed[cellIndex]; if (Attribute.IsDefined(property, typeof(TimeAttribute))) { try { TimeSpan ts = new TimeSpan(0, 0, (int)property.GetValue(data)); StringBuilder sb = new StringBuilder(); if ((int)ts.TotalHours > 0) { sb.Append((int)ts.TotalHours + "h"); } if (ts.Minutes > 0) { sb.Append(ts.Minutes + "m"); } if (ts.Seconds > 0) { sb.Append(ts.Seconds + "s"); } newCell.SetCellValue(sb.ToString()); } catch (Exception ex) { ILogger logger = ServiceProviderServiceExtensions.GetRequiredService <ILogger>( ServiceProviderExtension.ServiceProvider); logger.LogError($"Second转换失败:" + ex.Source + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException); newCell.SetCellValue(property.GetValue(data).ToString()); } } else { var propertyValue = property.GetValue(data); if (propertyValue == null) { newCell.SetCellValue(""); } else { newCell.SetCellValue(propertyValue.ToString()); } } newCell.CellStyle = styleCell; } } //统一设置列宽度 sheet.SetColumnWidth(fieldCount); }