wpf 导出Datatable 到excel

本文介绍如何在WPF应用中将DataTable数据导出到Excel文件,使用相关代码展示转换和导出过程。
摘要由CSDN通过智能技术生成

相关代码

using ConsoleApplication1.Export;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

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

    class ExportTest
    {
        private List<Student> Students = null;
        public ExportTest()
        {
            Students = new List<Student>(){
            new Student() { Name = "Jack", Age = 15, StudentId = 100 },
            new Student() { Name = "Smith", Age = 15, StudentId = 101 },
            new Student() { Name = "Smit", Age = 15, StudentId = 102 }
        };
            ListtoDataTableConverter converter = new ListtoDataTableConverter();
            DataTable dt = converter.ToDataTable(Students);
            this.ExporttoExcel(dt);
        }

        private void ExporttoExcel(DataTable table)
        {
            Console.WriteLine(CreateExcelDocument(table, @"D:\a.xlsx"));
        }

        /// <summary>
        /// Create an Excel file, and write it to a file.
        /// </summary>
        /// <param name="ds">DataSet containing the data to be written to the Excel.</param>
        /// <param name="excelFilename">Name of file to be written.</param>
        /// <returns>True if successful, false if something went wrong.</returns>
        public static bool CreateExcelDocument(DataTable ds, string excelFilename)
        {
            try
            {
                using (SpreadsheetDocument document = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
                {
                    WriteExcelFile(ds, document);
                }
                Trace.WriteLine("Successfully created: " + excelFilename);
                return true;
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Failed, exception thrown: " &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值