using System;
using System.Collections.Generic;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data;
using System.Data.OleDb;
using System.Runtime.InteropServices;

namespace Advantage_Final
{
    public static class My_DataTable_Extensions
    {

        // Export DataTable into an excel file with field names in the header line
        // - Save excel file without ever making it visible if filepath is given
        // - Don't save excel file, just make it visible if no filepath is given
        public static void ExportToExcel(this DataTable Tbl, string ExcelFilePath = null)
        {
            try
            {

                if (Tbl == null || Tbl.Columns.Count == 0)
                    throw new Exception("ExportToExcel: Null or empty input table!\n");

                if (System.IO.File.Exists(ExcelFilePath))
                {
                    Excel.Application excelEx = new Excel.Application();
                    Excel.Workbook workbook = excelEx.Workbooks.Open(ExcelFilePath);

                    // single worksheet
                    Excel._Worksheet workSheetEx = excelEx.ActiveSheet;
                    Excel.Range range = workSheetEx.UsedRange;
                    int colCount = range.Columns.Count;
                    int rowCount = range.Rows.Count;
                    int rowCount2 = range.Rows.Count;

                    for (int i = 0; i < Tbl.Rows.Count; i++)
                    {
                        // to do: format datetime values before printing
                        for (int j = 0; j < Tbl.Columns.Count; j++)
                        {
                            workSheetEx.Cells[(i + rowCount + 1), (j + 1)] = Tbl.Rows[i][j];
                        }
                    }
                    // column headings
          //          for (int i = 0; i < Tbl.Columns.Count; i++)
         //           {
         //               workSheetEx.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
         //           }

                    // rows
                    //for (int i = 0; i < Tbl.Rows.Count; i++)
             //           for (int i = 0; i < Tbl.Rows.Count; i++)
            //        {
                        // to do: format datetime values before printing
               //              int e = 0;
            //                int f = 0;
            //            for (int j = 0; j < Tbl.Columns.Count; j++)
              //          {
                         
                          //  workSheetEx.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
            //                workSheetEx.Cells[(rowCount + 2), (j + 1)] = Tbl.Rows[e][f];
            //                e++;
            //                f++;
                          
                //        }
               //     }

                    try
                    {
                        //excelEx.DisplayAlerts = false;
                        //workSheetEx.SaveAs(ExcelFilePath);
                        //excelEx.DisplayAlerts = true;
                        
                        // Close the workbook *Auto-Save*
                        workbook.Close(true, ExcelFilePath, false);

                        if (excelEx.Workbooks.Count == 0)
                        {
                            excelEx.Quit();
                            Marshal.FinalReleaseComObject(excelEx);
                        }
                        
                        //Marshal.ReleaseComObject(workSheetEx);
                        //Marshal.ReleaseComObject(excelEx);

                    }
                    catch (Exception ex)
                    {

                        throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                            + ex.Message);
                    }

                }

                if (!System.IO.File.Exists(ExcelFilePath))
                {
                    // load excel, and create a new workbook
                    Excel.Application excelApp = new Excel.Application();
                    Excel.Workbook workbook = excelApp.Workbooks.Add();

                    // single worksheet
                    Excel._Worksheet workSheet = excelApp.ActiveSheet;

                    // column headings
                    for (int i = 0; i < Tbl.Columns.Count; i++)
                    {
                        workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
                    }

                    // rows
                    for (int i = 0; i < Tbl.Rows.Count; i++)
                    {
                        // to do: format datetime values before printing
                        for (int j = 0; j < Tbl.Columns.Count; j++)
                        {
                            workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
                        }
                    }

                    // check fielpath
                    if (ExcelFilePath != null && ExcelFilePath != "")
                    {
                        try
                        {
                            //workSheet.SaveAs(ExcelFilePath);
                            //excelApp.Workbooks.Close();
                            //excelApp.Quit();
                            //excelApp = null;
                            
                            // Close the workbook *Auto-Save*
                            workbook.Close(true, ExcelFilePath, false);

                            if (excelApp.Workbooks.Count == 0)
                            {
                                excelApp.Quit();
                                Marshal.FinalReleaseComObject(excelApp);
                            }
                            
                        }
                        catch (Exception ex)
                        {

                            throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                                + ex.Message);
                        }
                    }
                    else    // no filepath is given
                    {
                        excelApp.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ExportToExcel: \n" + ex.Message);
            }

        }

        public static void ExportToExcel2(this DataTable Tbl, string ExcelFilePath = null)
        {
            try
            {
                if (Tbl == null || Tbl.Columns.Count == 0)
                    throw new Exception("ExportToExcel: Null or empty input table!\n");

                // load excel, and create a new workbook
                Excel.Application excelApp = new Excel.Application();
                excelApp.Workbooks.Add();

                // single worksheet
                Excel._Worksheet workSheet = excelApp.ActiveSheet;

                // column headings
                for (int i = 0; i < Tbl.Columns.Count; i++)
                {
                    workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
                }

                // rows
                for (int i = 0; i < Tbl.Rows.Count; i++)
                {
                    // to do: format datetime values before printing
                    for (int j = 0; j < Tbl.Columns.Count; j++)
                    {
                        workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
                    }
                }

                // check fielpath
                if (ExcelFilePath != null && ExcelFilePath != "")
                {
                    try
                    {
                        workSheet.SaveAs(ExcelFilePath);
                        excelApp.Quit();
                    }
                    catch (Exception ex)
                    {

                        throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                            + ex.Message);
                    }
                }
                else    // no filepath is given
                {
                    excelApp.Visible = true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ExportToExcel: \n" + ex.Message);
            }
        }
}
}

    
