How to export DataTable to Excel

后端 未结 21 2591
爱一瞬间的悲伤
爱一瞬间的悲伤 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 15:58

    In regards tuncalik's answer, which is great, especially if you want to have a little play with the code :) but it is putting my dates into Excel in American format i.e. 2nd March 2014 in the UK is 02/03/2014 but in the USA its 03/02/2014 with month 1st, then day of week after. I need to have it in UK format, any ideas please?

    I have checked it is stored in UK format in my DataTable and also my Excel is set to UK but for some reason when it makes the Excel document it thinks its USA (is this because Microsoft are a USA company :)

    I'll try experimenting with culture codes but not sure where to put that yet. Tried but this had no effect.

    p.s.

    I did have to change one line to get it to work by adding a 'cast' as below

    // single worksheet
    Excel._Worksheet workSheet = (Excel._Worksheet)excelApp.ActiveSheet;
    

    Update: I have achieved UK formatting of the dates by converting to LongDateTime format, its only a work around though.

    DateTime startDate = Convert.ToDateTime(myList[0].ToString());
    string strStartDate = startDate.ToLongDateString();
    DateTime endDate = Convert.ToDateTime(myList[myListTotalRows].ToString());
    string strEndDate = endDate.ToLongDateString();    
    

    cheers.

提交回复
热议问题