UserSchema.cs

本文介绍了一种使用C#将DataTable数据导出到Excel的方法,包括如何设置单元格格式、合并单元格以及自动调整列宽等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
// 添加引用 -> .NET -> Microsoft.Office.Interop.Excel(2003->11.0, 2007->12.0)

public static class UserSchema
{
    #region DataTable
    private static DataTable dataTable;

    static UserSchema()
    {
        dataTable = new DataTable("User");
        dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
        string[] columns = { "UserName", "UserEmail", "Content" };
        foreach (string name in columns)
        {
            dataTable.Columns.Add(name, typeof(String));
        }
        dataTable.Columns.Add("SendTime", typeof(DateTime));
        dataTable.Constraints.Add("Name", dataTable.Columns["UserName"], true);
    }

    public static DataTable UserTable
    {
        get { return dataTable; }
    }
    #endregion

    #region PrintToExcel
    public static void PrintToExcel(this DataTable table, string caption, params string[] columns)
    {
        Excel.Application xls = new Excel.Application();
        try
        {
            Excel.Workbook book = xls.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
            Excel.Worksheet sheet = book.ActiveSheet as Excel.Worksheet;
            xls.Visible = true;
            book.Password = "jinzhexian";
            sheet.Name = caption;
            sheet.get_Range("E4", Type.Missing).EntireColumn.NumberFormat = "yyyy年M月d日";
            Excel.Range range = sheet.get_Range("B1", Type.Missing).get_Resize(2, table.Columns.Count);
            range.MergeCells = true; // 合并单元格。
            range.Font.Size = 16;
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.Value2 = caption;
            range = range.get_Offset(1, 0).get_Resize(1, table.Columns.Count);
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.Value2 = columns;
            foreach (DataRow row in table.Rows)
            {
                range = range.get_Offset(1, 0);
                range.Value2 = row.ItemArray;
            }
            range = range.get_Offset(2, 0);
            range.MergeCells = true; // 合并单元格。
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
            range.Value2 = string.Format("打印日期: {0:yyyy'年'M'月'd'日'}", DateTime.Today);
            range.EntireColumn.AutoFit(); // 自动调整列宽。
            sheet.get_Range("A4", Type.Missing).Select();
            xls.SendKeys("%WFF", true); // 冻结拆分窗格 Microsoft Office 2003(%WF), 2007(%WFF)。
        }
        catch
        {
            xls.Quit();
        }
        finally
        {
            xls = null;
            GC.Collect();
        }
    }
    #endregion
}

Microsoft.Data.SqlClient.SqlException (0x80131904): 对象名 'Receive' 无效。 at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__195_0(Task`1 result) at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location --- at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread) --- End of stack trace from previous location --- at Dapper.SqlMapper.QueryAsync[T](IDbConnection cnn, Type effectiveType, CommandDefinition command) in /_/Dapper/SqlMapper.Async.cs:line 434 at Finance.Infrastructure.DapperDb.Query[T](String sql, Object parameters) in D:\2211A实训一\项目\erp\财务管理\Finance.Infrastructure\DapperDb.cs:line 23 at Finance.Api.Read.Applications.CommandHands.ReceiveQueryCommandHandlers.Handle(ReceiveQueryCommand request, CancellationToken cancellationToken) in D:\2211A实训一\项目\erp\财务管理\Finance.Api.Read\Applications\CommandHands\ReceiveQueryCommandHandlers.cs:line 32 at Finance.Api.Read.Controllers.ManagementController.ReceiveQuery(ReceiveQueryCommand request) in D:\2211A实训一\项目\erp\财务管理\Finance.Api.Read\Controllers\ManagementController.cs:line 26 at lambda_method5(Closure, Object) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context) ClientConnectionId:2a4e1948-5a2d-453c-a4b3-616d63e0b80c Error Number:208,State:1,Class:16 HEADERS ======= Accept: text/plain Connection: keep-alive Host: localhost:5047 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Accept-Encoding: gzip, deflate, br, zstd Accept-Language: zh-CN,zh;q=0.9 Referer: http://localhost:5047/swagger/index.html sec-ch-ua-platform: "Windows" sec-ch-ua: "Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138" sec-ch-ua-mobile: ?0 Sec-Fetch-Site: same-origin Sec-Fetch-Mode: cors Sec-Fetch-Dest: empty
最新发布
07-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值