用C#将Datagridview的内容存入Excel表

  使用如下代码,可将Datagridview的内容存入Excel表中:                

                                using Microsoft.Office.Core;
                                using Excel= Microsoft.Office.Interop.Excel;

                               

                                Excel.Application excelApp = new Excel.Application();

                                excelApp.Application.Workbooks.Add(true);            

                                object misValue = System.Reflection.Missing.Value;

                                if(File.Exists("D:\\List.xls"))

                                    {                

                                           File.Delete("D:\\List.xls");                

                                           excelApp.ActiveWorkbook.SaveAs(@"D:\List.xls", misValue, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);            

                                    }            

                               else            

                                    {                

                                           excelApp.ActiveWorkbook.SaveAs(@"D:\List.xls", misValue, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);                           

                                    }   

                                string myPath = "D:\\List.xls";                    

                                excelApp.Workbooks.Open(myPath);

                                for (int i = 0; i < dataGridView1.ColumnCount; i++)       

                                    {             

                                         for (int j = 0; j < dataGridView1.RowCount - 1; j++)                 

                                               {

                                                    excelApp.Cells[j + 2, i + 1] = dataGridView1[i, j].Value.ToString();

                                               }               

                                        excelApp.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;  

                                    }

                              excelApp.Visible = true;

         

用C#将Datagridview的内容存入Excel表

上一篇:在 Windows 上安装Rabbit MQ 指南


下一篇:C#三层构架