首页 > 解决方案 > 如何从控制台应用程序(.Net Core)导出 excel/pdf

问题描述

我试图从 .Net Core 创建一个控制台应用程序。希望能够进行一些 SQL 查询和计算,然后生成一些摘要报告并导出为 excel/pdf 格式。

我已经尝试过能够从 SQL 服务器数据库中选择一些 sql 查询的控制台应用程序。但是不确定如何在 .Net Core 的控制台应用程序中保存结果并导出为 excel/pdf 格式

using System;
using System.Data.SqlClient;


namespace SQLconnectionApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var SqlConnection = new SqlConnection("Server=myserver;Database=myDatabase;User Id=username;Password =password"))
            {
                using (var command = new SqlCommand("Select * from table", SqlConnection))
                {

                    SqlConnection.Open();

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {

                          Console.WriteLine($"id: {reader["id"]}, Name: {reader["Name"]}");

                        }
                    }
                 #the job want to do 
                 #collect the result from SQL server
                 #output some reports file in the folder
                }
            }
        }
    }
}

标签: excelpdf.net-core

解决方案


安装

dotnet add package Magicodes.IE.Pdf 

代码

创建 Dto

    public class Student
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

导出到文件

  public async Task ExportPdf()
        {
            var exporter = new PdfExporter();
            var result = await exporter.ExportListByTemplate("test.pdf", new List<Student>()
            {
                new Student
                {
                    Name = "MR.A",
                    Age = 18
                },
                new Student
                {
                    Name = "MR.B",
                    Age = 19
                },
                new Student
                {
                    Name = "MR.B",
                    Age = 20
                }
            });
        }

更多https://github.com/dotnetcore/Magicocodes.IE


推荐阅读