将数据导出为EXCEL文件

saveFileDialog1.Filter = "*.xls|.xls";
                saveFileDialog1.FileName = DateTime.Now.ToShortDateString();
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    savePath = saveFileDialog1.FileName;
                  

                    Object missing = Missing.Value;
                    Microsoft.Office.Interop.Excel.Application ExcelApplication = new Microsoft.Office.Interop.Excel.Application();
                    Microsoft.Office.Interop.Excel.Workbooks EWorkBooks = ExcelApplication.Workbooks;
                    Microsoft.Office.Interop.Excel.Workbook m_objWorkBook = EWorkBooks.Add(true);
                    Microsoft.Office.Interop.Excel.Sheets ESheets = m_objWorkBook.Sheets;
                    Microsoft.Office.Interop.Excel.Worksheet EWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ESheets[1];

                    for (int i = 1; i <= listSource.Count; i++)
                    {
                        for (int j = 0; j < columnTitle.Count; j++)
                        {
                            EWorkSheet.Cells[i, j + 1] = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();

                        }
                    }
                    EWorkSheet.SaveAs(savePath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                    m_objWorkBook.Close(false, missing, missing);
                    ExcelApplication.Quit();
                }

 

你可能感兴趣的:(将数据导出为EXCEL文件)