Esempio n. 1
0
        public void savetoExcel()
        {
            DataGridView dtg = new DataGridView();

            dtg = dataGridView6;

            string path = Directory.GetCurrentDirectory();

            for (int x = 0; x < 4; x++)
            {
                // creating Excel Application
                Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
                app.AlertBeforeOverwriting = false;
                // creating new WorkBook within Excel application
                Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);

                // creating new Excelsheet in workbook
                Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
                // see the excel sheet behind the program
                //  app.Visible = true;
                // get the reference of first sheet. By default its name is Sheet1.
                // store its reference to worksheet

                worksheet = workbook.Sheets["Sheet1"];
                worksheet = workbook.ActiveSheet;
                // changing the name of active sheet
                worksheet.Name = "Defect_Tracker";

                // storing header part in Excel
                for (int i = 1; i < dtg.Columns.Count + 1; i++)
                {
                    worksheet.Cells[1, i] = dtg.Columns[i - 1].HeaderText;
                }
                // storing Each row and column value to excel sheet

                for (int i = 0; i < dtg.Rows.Count - 2; i++)
                {
                    for (int j = 0; j < dtg.Columns.Count; j++)
                    {
                        try
                        {
                            worksheet.Cells[i + 2, j + 1] = dtg.Rows[i].Cells[j].Value.ToString();
                        }
                        catch (Exception ex) {
                        }
                    }
                }



                app.DisplayAlerts = false;
                //workbook.SaveAs(path + "\\MASTER-EXPORT.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows);

                workbook.SaveAs(path + "\\MASTER-EXPORT.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);

                app.Quit();
            }
            // save the application

            // Exit from the application
            Form3 frm3 = new Form3();

            frm3.Show();
            this.Hide();
            frm3.Focus();
            // Process.Start(path + "\\MASTER-EXPORT.xlsx");
            //  this.Close();
        }