How to export DataTable to Excel

后端 未结 21 2590
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  -上瘾入骨i
    2020-11-22 15:37

    Old thread - but thought i would throw my code in here. I wrote a little function to write a data table to a new excel sheet at a specified path (location). Also you will need to add a reference to microsoft excel 14.0 library.

    I pulled from this thread on writing anything to excel - How to write some data to excel file(.xlsx)

    i used that to extrapolate how to write a datatable

    *note in catch statements i have an errorhandler static class reference (you can ignore those)

     using excel = Microsoft.Office.Interop.Excel;
     using System.IO;
     using System.Data;
     using System.Runtime.InteropServices;
    
     //class and namespace wrapper is not shown in this example 
    
     private void WriteToExcel(System.Data.DataTable dt, string location)
        {
            //instantiate excel objects (application, workbook, worksheets)
            excel.Application XlObj = new excel.Application();
            XlObj.Visible = false;
            excel._Workbook WbObj = (excel.Workbook)(XlObj.Workbooks.Add(""));
            excel._Worksheet WsObj = (excel.Worksheet)WbObj.ActiveSheet;
    
            //run through datatable and assign cells to values of datatable
            try
            {
                int row = 1; int col = 1;
                foreach (DataColumn column in dt.Columns)
                {
                    //adding columns
                    WsObj.Cells[row, col] = column.ColumnName;
                    col++;
                }
                //reset column and row variables
                col = 1;
                row++;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //adding data
                    foreach (var cell in dt.Rows[i].ItemArray)
                    {
                        WsObj.Cells[row, col] = cell;
                        col++;
                    }
                    col = 1;
                    row++;
                }
                WbObj.SaveAs(location);
            }
            catch (COMException x)
            {                
                ErrorHandler.Handle(x);
            }
            catch (Exception ex)
            {               
                ErrorHandler.Handle(ex);
            }
            finally
            {
                WbObj.Close();                
            }
        }
    

提交回复
热议问题