Ejemplo n.º 1
0
        public static void Export_To_Excel(DataGridView dtGridView, string filename, string sheetName)
        {
            int    i, j;
            object missing = Type.Missing;

            Excel.ApplicationClass excellApp;
            excellApp = new Excel.ApplicationClass();
            excellApp.Application.Workbooks.Add(true);

            try
            {
                // Add columns name to excel file
                for (i = 0; i < dtGridView.Columns.Count; i++)
                {
                    excellApp.Cells[1, i + 1] = dtGridView.Columns[i].Name;
                }
                for (i = 0; i < dtGridView.Rows.Count; i++)
                {
                    for (j = 0; j < dtGridView.Columns.Count; j++)
                    {
                        excellApp.Cells[i + 2, j + 1] = dtGridView.Rows[i].Cells[j].Value;
                    }
                }
                //excellApp.Save(("Loinhuan.xls");
                Excel._Worksheet worksheet = (Excel._Worksheet)excellApp.ActiveSheet;
                worksheet.Activate();
                worksheet.Name = sheetName;
                worksheet.SaveAs(filename, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                //excellApp.Workbooks[1].SaveCopyAs(@"D:\Project\SVN\Source\Quanlyloinhuan\Loinhuan.xls");
                excellApp.Quit();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }