How to export DataTable to Excel

后端 未结 21 2567
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 15:36

How can I export a DataTable to Excel in C#? I am using Windows Forms. The DataTable is associated with a DataGridView control. I have

21条回答
  •  攒了一身酷
    2020-11-22 16:02

    With the EPPlus NuGet package, it's very easy.

    public class TestObject
    {
        public int Col1 { get; set; }
        public int Col2 { get; set; }
        public string Col3 { get; set; }
        public DateTime Col4 { get; set; }
    }
    
    [TestMethod]
    public void LoadFromCollection_MemberList_Test()
    {
        //https://stackoverflow.com/questions/32587834/epplus-loadfromcollection-text-converted-to-number/32590626#32590626
    
        var TestObjectList = new List();
        for (var i = 0; i < 10; i++)
            TestObjectList.Add(new TestObject {Col1 = i, Col2 = i*10, Col3 = (i*10) + "E4"});
    
        //Create a test file
        var fi = new FileInfo(@"c:\temp\LoadFromCollection_MemberList_Test.xlsx");
        if (fi.Exists)
            fi.Delete();
    
        using (var pck = new ExcelPackage(fi))
        {
            //Do NOT include Col1
            var mi = typeof (TestObject)
                .GetProperties()
                .Where(pi => pi.Name != "Col1")
                .Select(pi => (MemberInfo)pi)
                .ToArray();
    
            var worksheet = pck.Workbook.Worksheets.Add("Sheet1");
            worksheet.Cells.LoadFromCollection(
                TestObjectList
                , true
                , TableStyles.Dark1
                , BindingFlags.Public| BindingFlags.Instance
                , mi);
    
            pck.Save();
        }
    }
    

    Notice that Col1 is NOT in the output:

提交回复
热议问题