Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, January 28, 2014

How to Change Pixel Color of Image in C#


Copied from the Site: http://stackoverflow.com/questions/17208254/how-to-change-pixel-color-of-an-image-in-c-net

var originalColor = scrBitmap.GetPixel(i, j);
if (originalColor.R == 0 && originalColor.G == 0 && originalColor.B == 0)
    newBitmap.SetPixel(i, j, Color.FromArgb(originalColor.A, Color.Red));
Now you'll see that it works but it takes a very long time to process each image: GetPixel andSetPixel are pretty slow (primary because they check and calculate everything for each call). It's much better to handle bitmap data directly. If you know the image format in advance (32 bit-per-pixel to 8 bit-per-pixel) then you can do it much much faster with LockBits:
The Bitmap class provides the LockBits and corresponding UnlockBits methods which enable you to fix a portion of the bitmap pixel data array in memory, access it directly and finally replace the bits in the bitmap with the modified data. LockBits returns a BitmapData class that describes the layout and position of the data in the locked array.
static unsafe Bitmap ReplaceColor(Bitmap source,
                                  Color toReplace,
                                  Color replacement)
{
  const int pixelSize = 4; // 32 bits per pixel

  Bitmap target = new Bitmap(
    source.Width,
    source.Height,
    PixelFormat.Format32bppArgb);

  BitmapData sourceData = null, targetData = null;

  try
  {
    sourceData = source.LockBits(
      new Rectangle(0, 0, source.Width, source.Height),
      ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

    targetData = target.LockBits(
      new Rectangle(0, 0, target.Width, target.Height),
      ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

    for (int y = 0; y < source.Height; ++y)
    {
      byte* sourceRow = (byte*)sourceData.Scan0 + (y * sourceData.Stride);
      byte* targetRow = (byte*)targetData.Scan0 + (y * targetData.Stride);

      for (int x = 0; x < source.Width; ++x)
      {
        byte b = sourceRow[x * pixelSize + 0];
        byte g = sourceRow[x * pixelSize + 1];
        byte r = sourceRow[x * pixelSize + 2];
        byte a = sourceRow[x * pixelSize + 3];

        if (toReplace.R == r && toReplace.G == g && toReplace.B == b)
        {
          r = replacement.R;
          g = replacement.G;
          b = replacement.B;
        }

        targetRow[x * pixelSize + 0] = b;
        targetRow[x * pixelSize + 1] = g;
        targetRow[x * pixelSize + 2] = r;
        targetRow[x * pixelSize + 3] = a;
      }
    }
  }
  finally
  {
    if (sourceData != null)
      source.UnlockBits(sourceData);

    if (targetData != null)
      target.UnlockBits(targetData);
  }

  return target;
}

Note: To run the unsafe code in C#, you have to do: Open the properties for the project, go to the Build tab and check the Allow unsafe codecheckbox.

Friday, March 29, 2013

LINQ Examples


Check it out http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
http://weblogs.asp.net/scottgu/archive/2006/05/14/446412.aspx

LINQ Advantage:

  1. Abstraction: This is especially true with LINQ-to-Entities. This abstraction also allows the framework to add additional improvements that you can easily take advantage of. PLINQ is an example of adding multi-threading support to LINQ. Code changes are minimal to add this support. It would be MUCH harder to do this data access code that simply calls sprocs.
  2. Debugging support: I can use any .NET debugger to debug the queries. With sprocs, you cannot easily debug the SQL and that experience is largely tied to your database vendor (MS SQL Server provides a query analyzer, but often that isn't enough).
  3. Vendor agnostic: LINQ works with lots of databases and the number of supported databases will only increase. Sprocs are not always portable between databases, either because of varying syntax or feature support (if the database supports sprocs at all).
Summary:
1. when talking single DB table and small set of data CRUD, LINQ is as fast as SP. But for much more complicated logic, stored procedure is more performance tweakable.
2. Easier to port to another DB - no procs to port.

LINQ Disadvantage:

  1. Network traffic: sprocs need only serialize sproc-name and argument data over the wire while LINQ sends the entire query. This can get really bad if the queries are very complex. However, LINQ's abstraction allows Microsoft to improve this over time.
  2. Recompiling: If you need to make changes to the way you do data access, you need to recompile, version, and redeploy your assembly. Sprocs can sometimes allow a DBA to tune the data access routine without a need to redeploy anything.
Summary:
  • Store Procedure Prevent reverse engineering (if created With Encryption, of course)
  • Store Procedure Better centralization of database access
  • Store Procedure Ability to change data model transparently (without having to deploy new clients); especially handy if multiple programs access the same data model

In short:

Both LINQ and SQL have their places. Both have their disadvantages and advantages.
Sometimes for complex data retrieval you might need stored procs. And sometimes you may want other people to use your stored proc in Sql Server Management Studio.
Linq to Entities is great for fast CRUD development.
Sure you can build an app using only one or the other. Or you can mix it up. It all comes down to your requirements. But SQL stored procs will no go away any time soon.

Note: 1) LINQ works with lots of databases " But LINQTOSQL only supports SQL Server.

Friday, March 8, 2013

Numeric TextBox in C#


Numeric TextBox Control  http://msdn.microsoft.com/en-us/library/ms229644%28v=vs.80%29.aspx

1. Integer

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
} 

2. Decimal

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    // only allow one decimal point
    if (e.KeyChar == '.' 
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    } 
} 

Sunday, October 7, 2012

How to catch multikey press in C#


KeyEventArgs e;
if(e.KeyData == (Keys.Control | Keys.C)
    MessageBox.Show("Ctrl+C pressed...");

Keys KeyData

if(KeyData == (Keys.Control | Keys.C)
    MessageBox.Show("Ctrl+C pressed...");


Sunday, July 22, 2012

Excel to PDF in C# Win Form


These link have important information about this topic:

http://stackoverflow.com/questions/769246/xls-to-pdf-conversion-inside-net

http://stackoverflow.com/questions/5499562/excel-to-pdf-c-sharp-library

http://tinyway.wordpress.com/2011/03/30/how-to-convert-office-documents-to-pdf-using-open-office-in-c/


Using Open Office:-

1)Install the Open Office and Open Office SDK
2)Add references in the project i.e, Add following dll's from OpenOffice SDK file:
cli_basetypes.dll
cli_cppuhelper.dll
cli_oootypes.dll
cli_ure.dll
cli_uretypes.dll 


Copy and Paste the below code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using uno.util;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.util;
using System.Diagnostics;
namespace PDFGenerator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string excelFile = "file:///C:/244.xls";
            string pdfFile = "file:///C:/244.pdf";

            int NewOpenOfficeID = 0;
            int PreviousTotalOpenOfficeID = 0;
            int NextTotalOpenOfficeID = 0;
            foreach (Process p in Process.GetProcessesByName("soffice.bin"))
                PreviousTotalOpenOfficeID = PreviousTotalOpenOfficeID + p.Id;
            if (PreviousTotalOpenOfficeID > 0)
            {
                MessageBox.Show("Please Close the Open Office before going to further","Mesaage");
                return;
            }
            else
            {
                // Start OpenOffce or get a reference to an existing session
                XComponentContext localContext = Bootstrap.bootstrap();
                XMultiServiceFactory multiServiceFactory = (XMultiServiceFactory)localContext.getServiceManager();
                XComponentLoader componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");

                foreach (Process p in Process.GetProcessesByName("soffice.bin"))
                    NextTotalOpenOfficeID = NextTotalOpenOfficeID + p.Id;

                NewOpenOfficeID = NextTotalOpenOfficeID - PreviousTotalOpenOfficeID;

                // Open file hidden in read-only mode
                PropertyValue[] loadProps = new PropertyValue[2];
                loadProps[0] = new PropertyValue();
                loadProps[0].Name = "ReadOnly";
                loadProps[0].Value = new uno.Any(true);
                loadProps[1] = new PropertyValue();
                loadProps[1].Name = "Hidden";
                loadProps[1].Value = new uno.Any(true);

                // Open the file
                XComponent sourceDoc = componentLoader.loadComponentFromURL(excelFile, "_blank", 0, loadProps);

                // Conversion parameters - overwrite existing file, use PDF exporter
                PropertyValue[] conversionProperties = new PropertyValue[3];
                conversionProperties[0] = new PropertyValue();
                conversionProperties[0].Name = "Overwrite";
                conversionProperties[0].Value = new uno.Any(true);
                conversionProperties[1] = new PropertyValue();
                conversionProperties[1].Name = "FilterName";
                conversionProperties[1].Value = new uno.Any("calc_pdf_Export");

                // Set PDF export parameters
                PropertyValue[] filterData = new PropertyValue[3];

                // JPEG compression quality 70
                filterData[0] = new PropertyValue();
                filterData[0].Name = "Quality";
                filterData[0].Value = new uno.Any(70);
                filterData[0].State = PropertyState.DIRECT_VALUE;

                // Max image resolution 300dpi
                filterData[1] = new PropertyValue();
                filterData[1].Name = "ReduceImageResolution";
                filterData[1].Value = new uno.Any(true);
                filterData[1].State = PropertyState.DIRECT_VALUE;
                filterData[2] = new PropertyValue();
                filterData[2].Name = "MaxImageResolution";
                filterData[2].Value = new uno.Any(300);
                filterData[2].State = PropertyState.DIRECT_VALUE;

                conversionProperties[2] = new PropertyValue();
                conversionProperties[2].Name = "FilterData";
                conversionProperties[2].Value = new uno.Any(filterData.GetType(), filterData);

                // Save as PDF
                XStorable xstorable = (XStorable)sourceDoc;
                xstorable.storeToURL(pdfFile, conversionProperties);

                // Close document
                ((XCloseable)sourceDoc).close(false);
                ((XCloseable)xstorable).close(false);

                Process pro = Process.GetProcessById(NewOpenOfficeID);
                pro.Kill();
            }

        }
    }
}
 

Monday, May 7, 2012

Number to Words in c#


//Below content is copied some other sites
//--------------------------------------------
//First Example
//-------------------------------------------
public static string NumberToWords(int number)
        {
            if (number == 0)
                return "zero";

            if (number < 0)
                return "minus " + NumberToWords(Math.Abs(number));

            string words = "";

            if ((number / 10000000) > 0)
            {
                words += NumberToWords(number / 10000000) + " crore ";
                number %= 10000000;
            }

            if ((number / 100000) > 0)
            {
                words += NumberToWords(number / 100000) + " lakh ";
                number %= 100000;
            }

            if ((number / 1000) > 0)
            {
                words += NumberToWords(number / 1000) + " thousand ";
                number %= 1000;
            }

            if ((number / 100) > 0)
            {
                words += NumberToWords(number / 100) + " hundred ";
                number %= 100;
            }

            if (number > 0)
            {
                if (words != "")
                    words += "and ";

                string[] unitsMap = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
                string[] tensMap = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

                if (number < 20)
                    words += unitsMap[number];
                else
                {
                    words += tensMap[number / 10];
                    if ((number % 10) > 0)
                        words += "-" + unitsMap[number % 10];
                }
            }

            return words;
        }

 //-------------------------------------------------------------------
 .// Second Example
 //------------------------------------------------------------
private void button1_Click(object sender, EventArgs e)
        {
            textBox2.Text = changeCurrencyToWords(textBox1.Text);
            if (textBox2.Text.Contains("and Crore"))
            {
                textBox2.Text = textBox2.Text.Replace("and Crore", "");
            }
            if(textBox2.Text.Contains("and Lakh"))
            {
                textBox2.Text=textBox2.Text.Replace(" and Lakh", "");
            }
            if (textBox2.Text.Contains("and Thousand"))
            {
                textBox2.Text=textBox2.Text.Replace(" and Thousand", "");
            }
            if (textBox2.Text.Contains("and Hundred"))
            {
                textBox2.Text = textBox2.Text.Replace(" and Hundred", "");
            }
        }
       

        public String changeNumericToWords(double numb)
        {
            String num = numb.ToString();
            return changeToWords(num, false);
        }
        public String changeCurrencyToWords(String numb)
        {
            return changeToWords(numb, true);
        }
        public String changeNumericToWords(String numb)
        {
            return changeToWords(numb, false);
        }
        public String changeCurrencyToWords(double numb)
        {
            return changeToWords(numb.ToString(), true);
        }
        private String changeToWords(String numb, bool isCurrency)
        {
            String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";
            String endStr = (isCurrency) ? ("Rupees Only") : ("");
            try
            {
                int decimalPlace = numb.IndexOf(".");
                if (decimalPlace > 0)
                {
                    wholeNo = numb.Substring(0, decimalPlace);
                    points = numb.Substring(decimalPlace + 1);
                    if (Convert.ToInt32(points) > 0)
                    {
                        andStr = (isCurrency) ? ("and") : ("point");// just to separate whole numbers from points/cents
                        endStr = (isCurrency) ? ("Paisa " + endStr) : ("");
                        pointStr = translateCents(points);
                    }
                }
                val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);
            }
            catch { ;}
            return val;
        }
        private String translateWholeNumber(String number)
        {
            string word = "";
            try
            {
                bool beginsZero = false;//tests for 0XX
                bool isDone = false;//test if already translated
                double dblAmt = (Convert.ToDouble(number));
                //if ((dblAmt > 0) && number.StartsWith("0"))
                if (dblAmt > 0)
                {//test for zero or digit zero in a nuemric
                beginsZero = number.StartsWith("0");
                int numDigits = number.Length;
                int pos = 0;//store digit grouping
                String place = "";//digit grouping name:hundres,thousand,etc...
                switch (numDigits)
                {
                    case 1://ones' range
                    word = ones(number);
                    isDone = true;
                    break;
                    case 2://tens' range
                    word = tens(number);
                    isDone = true;
                    break;
                    case 3://hundreds' range
                    pos = (numDigits % 3) + 1;
                    place = " Hundred ";
                    break;
                    case 4://thousands' range
                    case 5:
                    pos = (numDigits % 4) + 1;
                    place = " Thousand ";
                    break;
                    case 6://lakh' range
                    case 7:
                    pos = (numDigits % 6) + 1;
                    place = " Lakh ";
                    break;
                    case 8://Crore' range
                    case 9:
                    pos = (numDigits % 8) + 1;
                    place = " Crore ";
                    break;
                    case 10://Arab's range
                   
                    //add extra case options for anything above Billion...
                    default:
                    isDone = true;
                    break;
                }
                if (!isDone)
                {
                    //if transalation is not done, continue...(Recursion comes in now!!)
                    word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
                    //check for trailing zeros
                    if (beginsZero)
                        word = " and " + word.Trim();
                }
                //ignore digit grouping names
                if (word.Trim().Equals(place.Trim()))
                    word = "";
                }
            }
            catch { ;}
            return word.Trim();
        }
        private String tens(String digit)
        {
            int digt = Convert.ToInt32(digit);
            String name = null;
            switch (digt)
            {
                case 10:
                name = "Ten";
                break;
                case 11:
                name = "Eleven";
                break;
                case 12:
                name = "Twelve";
                break;
                case 13:
                name = "Thirteen";
                break;
                case 14:
                name = "Fourteen";
                break;
                case 15:
                name = "Fifteen";
                break;
                case 16:
                name = "Sixteen";
                break;
                case 17:
                name = "Seventeen";
                break;
                case 18:
                name = "Eighteen";
                break;
                case 19:
                name = "Nineteen";
                break;
                case 20:
                name = "Twenty";
                break;
                case 30:
                name = "Thirty";
                break;
                case 40:
                name = "Fourty";
                break;
                case 50:
                name = "Fifty";
                break;
                case 60:
                name = "Sixty";
                break;
                case 70:
                name = "Seventy";
                break;
                case 80:
                name = "Eighty";
                break;
                case 90:
                name = "Ninety";
                break;
                default:
                if (digt > 0)
                {
                    name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
                }
                break;
            }
            return name;
        }
        private String ones(String digit)
        {
            int digt = Convert.ToInt32(digit);
            String name = "";
            switch (digt)
            {
                case 1:
                name = "One";
                break;
                case 2:
                name = "Two";
                break;
                case 3:
                name = "Three";
                break;
                case 4:
                name = "Four";
                break;
                case 5:
                name = "Five";
                break;
                case 6:
                name = "Six";
                break;
                case 7:
                name = "Seven";
                break;
                case 8:
                name = "Eight";
                break;
                case 9:
                name = "Nine";
                break;
            }
            return name;
        }
        private String translateCents(String cents)
        {
            String cts = "", digit = "", engOne = "";
            for (int i = 0; i < cents.Length; i++)
            {
                digit = cents[i].ToString();
                if (digit.Equals("0"))
                {
                    engOne = "Zero";
                }
                else
                {
                    engOne = ones(digit);
                }
                cts += " " + engOne;
            }
            return cts;
        }

Thursday, April 5, 2012

Modify Excel Properties through C#


            Excel._Application app=new Excel.Application();
            Excel.Workbooks Wbs=app.Workbooks;;
            Excel.Workbook Wb= Wbs.Add(1);;
            //Excel.Worksheets Osheets;
            Excel.Worksheet Osheet=(Excel.Worksheet)Wb.ActiveSheet;
           
                Osheet.PageSetup.Orientation = XlPageOrientation.xlLandscape;

                Osheet.PageSetup.LeftMargin = double.Parse("42.05");//left margin(0.58) * 72.5
                Osheet.PageSetup.RightMargin = double.Parse("31.09");//right margin(0.44) * 72.5
                Osheet.PageSetup.TopMargin = double.Parse("42.05");
                Osheet.PageSetup.BottomMargin = double.Parse("31.09");
                Osheet.PageSetup.HeaderMargin = double.Parse("0");
                Osheet.PageSetup.FooterMargin = double.Parse("0");

                Range oRng = Osheet.get_Range(Osheet.Cells[1, 1], Osheet.Cells[1, 10]);
                oRng.Merge(Type.Missing);              
                           
                Osheet.Cells[1, 1] = "Nishant";                                       
                Range oRng = (Range)Osheet.Cells[1, 1]
                oRng.EntireColumn.Font.Name = "Arial";
                oRng.EntireColumn.Font.Size = "11";
                oRng.Font.Bold = true;
                oRng.Font.Underline = true;
                oRng.EntireColumn.WrapText = true;
                oRng.EntireColumn.NumberFormat = "@";
                oRng.EntireColumn.VerticalAlignment = XlVAlign.xlVAlignCenter;
                oRng.HorizontalAlignment = XlHAlign.xlHAlignCenter;

Monday, February 13, 2012

Combined multiple pdf into one pdf in c#

A datatable with columns at run time


01 public class Customer
02    {
03        private string _firstName;
04        private string _lastName;
05        private string _email;
06 
07        public string FirstName
08        {
09            get { return _firstName; }
10            set { _firstName = value; }
11        }
12 
13        public string LastName
14        {
15            get { return _lastName; }
16            set { _lastName = value; }
17        }
18 
19        public string FullName
20        {
21            get { return _firstName + " " + _lastName; }
22        }
23 
24        public string Email
25        {
26            get { return _email; }
27            set { _email = value; }
28        }
29      }








------------------------------------------------
 //DataGrid1.DataSource=GetCustomers();
// DataGrid1.DataBind();
DataTable dt=new DataTable();
dt=GetCustomers();
-------------------------------------------------
09        private List<Customer> GetCustomers()
10        {
11            List<Customer> customers = new List<Customer>();
12 
13            for (int i = 1; i <= 20; i++)
14            {
15                Customer customer = new Customer();
16                customer.FirstName = "FirstName" + i;
17                customer.LastName = "LastName" + i;
18                customer.Email = "Email" + i;
19                customers.Add(customer);
20            }
21 
22            return customers;
23        }







Sunday, November 20, 2011

Fast Exporting from Dataset and more than 65536 rows


Important:    outputPath file extention must be xls. like "Test.xls" Because In excel 2007 (office 12), while it is writing to file (at SaveAs) Compatibility Checker opens and ask me to continue. i Used excelApp.DisplayAlerts = false; but when i open excel document, i saw just 65536 rows.


public static void ExportToExcel(DataSet dataSet, string outputPath)
    {
  
        System.Type moAppType;
        // if u use excell 2003 and 2007 on same project, make sure true object u loaded.
        moAppType = System.Type.GetTypeFromProgID("Excel.Application.12");
       
       // xlApp = (Excel.Application)moApp;
        // Create the Excel Application object
        Application excelApp = (Microsoft.Office.Interop.Excel.Application)System.Activator.CreateInstance(moAppType);
        excelApp.DisplayAlerts = false;
        
 
        // Create a new Excel Workbook
        Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
 
        int sheetIndex = 0;
 
        // Copy each DataTable
        foreach (System.Data.DataTable dt in dataSet.Tables)
        {
 
            // Copy the DataTable to an object array
            object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
 
            // Copy the column names to the first row of the object array
            for (int col = 0; col < dt.Columns.Count; col++)
            {
                rawData[0, col] = dt.Columns[col].ColumnName;
            }
 
            // Copy the values to the object array
            for (int col = 0; col < dt.Columns.Count; col++)
            {
                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
                }
            }
 
            // Calculate the final column letter
            string finalColLetter = string.Empty;
            string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            int colCharsetLen = colCharset.Length;
 
            if (dt.Columns.Count > colCharsetLen)
            {
                finalColLetter = colCharset.Substring(
                    (dt.Columns.Count - 1) / colCharsetLen - 1, 1);
            }
 
            finalColLetter += colCharset.Substring(
                    (dt.Columns.Count - 1) % colCharsetLen, 1);
 
            // Create a new Sheet
            Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(
                excelWorkbook.Sheets.get_Item(++sheetIndex),
                Type.Missing, 1, XlSheetType.xlWorksheet);
 
            excelSheet.Name = dt.TableName;
            
 
            // Fast data export to Excel
            string excelRange = string.Format("A1:{0}{1}",
                finalColLetter, dt.Rows.Count + 1);
 
            excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
 
            // Mark the first row as BOLD
            ((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
        }
       
        // Save and Close the Workbook
        
        excelWorkbook.SaveAs(outputPath, XlFileFormat.xlExcel12, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        excelWorkbook.Close(true, Type.Missing, Type.Missing);
        excelWorkbook = null;
 
        // Release the Application object
        excelApp.Quit();
        excelApp = null;
 
        // Collect the unreferenced objects
        GC.Collect();
        GC.WaitForPendingFinalizers();
 
    }