Monday 28 March 2016

Exception logging and export datatable to excel using c#

Log exception to Text

Log.ErrorLog(ex, "excel"); to export to text file in your exception handling

Log Datatable to excel

Log.Excel_FromDataTable(datatable);

below class will export to text file and excel.

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace DataMigrationHDM
{
    internal class Log
    {
        public static void Excel_FromDataTable(System.Data.DataTable dt)
        {
            try
            {


                // Create an Excel object and add workbook...

                ApplicationClass excel = new ApplicationClass();

                Workbook workbook = excel.Application.Workbooks.Add(true); // true for object template???

                // Add column headings...
                int iCol = 0;
                foreach (DataColumn c in dt.Columns)
                {
                    iCol++;
                    excel.Cells[1, iCol] = c.ColumnName;
                }
                // for each row of data...
                int iRow = 0;
                foreach (DataRow r in dt.Rows)
                {
                    iRow++;

                    // add each row's cell data...
                    iCol = 0;
                    foreach (DataColumn c in dt.Columns)
                    {
                        iCol++;
                        excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
                    }
                }

                // Global missing reference for objects we are not defining...
                object missing = System.Reflection.Missing.Value;
                Worksheet worksheet = (Worksheet)excel.ActiveSheet;
               
                string RDir = Directory.GetCurrentDirectory();
                string sYear = DateTime.Now.Year.ToString();
                string sMonth = DateTime.Now.Month.ToString(CultureInfo.InvariantCulture);
                string sDay = DateTime.Now.Day.ToString();
                string dirPath = RDir + @"\ReleasedStandards\" + sMonth + "-" + sDay + "-" + sYear;
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                //string dateT = DateTime.Now.ToLongDateString();

                string sErrorTime = sDay + "-" + sMonth + "-" + sYear + " " + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute;
                workbook.SaveAs(dirPath + "\\Report_" + sErrorTime + ".xls",
           XlFileFormat.xlXMLSpreadsheet, missing, missing,
            false, false, XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);

                // If wanting to make Excel visible and activate the worksheet...
                excel.Visible = true;

                ((_Worksheet)worksheet).Activate();

                // //format excel on run time 



                // If wanting excel to shutdown...
                ((_Application)excel).Quit();
                MessageBox.Show("Report Generated", "Maintenance Tool...", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error in webservice while Saving Excel.", "Maintenance Tool...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ErrorLog(ex, "Writng to excel");

            }
        }
        public static void ErrorLog(Exception ex,String info)
        {
            StreamWriter sw = null;

            try
            {
                string sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " +
                                    DateTime.Now.ToLongTimeString().ToString() + " ==> ";

                string sPathName = Directory.GetCurrentDirectory();

                string sYear = DateTime.Now.Year.ToString();
                string sMonth = DateTime.Now.Month.ToString();
                string sDay = DateTime.Now.Day.ToString();

                string sErrorTime = sDay + "-" + sMonth + "-" + sYear;
                string dirPath = sPathName + @"\Logs\";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                sw = new StreamWriter(dirPath + "\\DocumentLibrary_ErrorLog_" + sErrorTime + ".txt", true);

                sw.WriteLine(sLogFormat + ex.Message + ex.StackTrace + info);
                sw.Flush();

            }
            catch (Exception ex1)
            {
                ErrorLog(ex1,"Lib");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                    sw.Close();
                }
            }

        }
    }
}

No comments:

Post a Comment