I have created excel workbook using .NET interop. The excel workbook is created successfully through my C# code. When the user makes any changes in the excel, I want to do some stuff. I have used the ExcelWorkSheet.Change event. But this event is not firing. Here is my code-
using Excel = Microsoft.Office.Interop.Excel;
public class xxx
{
static Excel.Application xlApp;
static Excel.Workbook xlWorkBook;
static Excel.Worksheet xlWorkSheet;
static Excel.Worksheet xlWorkSheet1;
static Excel.DocEvents_ChangeEventHandler EventDel_CellsChange;
public static void ExportToExcel()
{
xlApp = new Excel.ApplicationClass();
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
---------------- data is dumped to the excel here----------------
((Microsoft.Office.Interop.Excel._Worksheet)xlWorkSheet).Activate();
xlApp.EnableEvents = true;
EventDel_CellsChange = new Excel.DocEvents_ChangeEventHandler(Worksheet_Change);
xlWorkSheet.Change += EventDel_CellsChange;
xlWorkBook.SaveAs("D:\\Test.xlsx", Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlShared, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet1);
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=Test.xlsx;");
response.TransmitFile(("D:\\Test.xlsx");
response.Flush();
response.End();
}
public static void Worksheet_Change(Excel.Range Target)
{
try
{
xlApp.EnableEvents = false;
Excel.Range range = xlWorkSheet.get_Range("Y2");
range.Formula = "=A2";
}
catch (Exception ex)
{
}
finally
{
xlApp.EnableEvents = true;
}
}
}
No change is reflected in the Excel file when the user makes some changes.
Please help me out.
Thanks in advance
The Worksheet_Change event is not global - it only applies to that particular worksheet. In your code you wire up the event handler to the xlSheet1.Change event, then close the workbook and release all the Excel objects.
EDIT: I popped your code behind a Form and adapted it slightly. I could get the event to fire and the formula in cell Y2 is set. I'm not 100% sure of your circumstances, but try this code and then compare with your own. Hope it helps.
public partial class Form1 : Form
{
private static Excel.Application xlApp;
private static Excel.Workbook xlWorkBook;
private static Excel.Worksheet xlWorkSheet;
private static Excel.Worksheet xlWorkSheet1;
private static Excel.DocEvents_ChangeEventHandler EventDel_CellsChange;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
xlApp = new Excel.Application();
xlApp.Visible = true;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
//---------------- data is dumped to the excel here----------------
((Microsoft.Office.Interop.Excel._Worksheet)xlWorkSheet).Activate();
xlApp.EnableEvents = true;
EventDel_CellsChange = new Excel.DocEvents_ChangeEventHandler(Worksheet_Change);
xlWorkSheet.Change += EventDel_CellsChange;
}
public static void Worksheet_Change(Excel.Range Target)
{
try
{
xlApp.EnableEvents = false;
Excel.Range range = xlWorkSheet.get_Range("Y2");
range.Formula = "=A2";
}
catch (Exception ex)
{
}
finally
{
xlApp.EnableEvents = true;
}
}
}
Related
I have this excel file that currently writes contents from my c# application to its cell contents:
private void button8_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = comboBox2.Text;
xlWorkSheet.Cells[1, 2] = textBox5.Text;
xlWorkSheet.Cells[1, 3] = textBox2.Text;
xlWorkSheet.Cells[1, 4] = comboBox3.Text;
xlWorkSheet.Cells[1, 5] = textBox3.Text;
xlWorkSheet.Cells[1, 6] = comboBox1.Text;
xlWorkBook.SaveAs(#"cross_check.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
MessageBox.Show("Excel file created succcessfully");
}
}
How do I append to this same file which has already been created?To expand further, currently I have to specify the cells the values have to be added to. How do I like increment in some fashion as to say no matter how many times the user hits the add to file button it should just increment the previous pattern.
eg. I have :
xlWorkSheet.Cells[1, 1] = comboBox2.Text;
xlWorkSheet.Cells[1, 2] = textBox5.Text;
xlWorkSheet.Cells[1, 3] = textBox2.Text;
xlWorkSheet.Cells[1, 4] = comboBox3.Text;
xlWorkSheet.Cells[1, 5] = textBox3.Text;
xlWorkSheet.Cells[1, 6] = comboBox1.Text;
Upon clicking the button, how would I make it now follow this pattern:
xlWorkSheet.Cells[2, 1] = comboBox2.Text;
xlWorkSheet.Cells[2, 2] = textBox5.Text;
xlWorkSheet.Cells[2, 3] = textBox2.Text;
xlWorkSheet.Cells[2, 4] = comboBox3.Text;
xlWorkSheet.Cells[2, 5] = textBox3.Text;
xlWorkSheet.Cells[2, 6] = comboBox1.Text;
I suppose you use the Excel object through the
Microsoft.Office.Interop.Excel reference. Then you have to modify your code as
follows
private void button8_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlApp; //Declare the
//Excel object
try
{
xlApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch (Exception ee)
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
}
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook=xlApp.Workbooks.Add(misValue);
try
{
xlWorkBook = xlApp.Workbooks.Open(#"cross_check.xls");//,
}
catch (Exception ex)
{
;//
}
Microsoft.Office.Interop.Excel.Range range;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet =
(Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int rownum = 1;
int MAX_ROWS=30000; //You may define your own limit
bool written = true;
range = xlWorkSheet.UsedRange;
while ((written) && (rownum<MAX_ROWS))
{
var test = (range.Cells[rownum, 1] as
Microsoft.Office.Interop.Excel.Range).Value2;
if (test != null)
{
rownum++;
}
else
{
written = false;
}
}
if (written == false)
{
xlWorkSheet.Cells[rownum, 1] = comboBox2.Text;
xlWorkSheet.Cells[rownum, 2] = textBox5.Text;
xlWorkSheet.Cells[rownum, 3] = textBox2.Text;
xlWorkSheet.Cells[rownum, 4] = comboBox3.Text;
xlWorkSheet.Cells[rownum, 5] = textBox3.Text;
xlWorkSheet.Cells[rownum, 6] = comboBox1.Text;
}
xlApp.DisplayAlerts = false; //Disables the prompts
xlWorkBook.SaveAs(#"cross_check.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, misValue, misValue, misValue, misValue, misValue);
xlApp.DisplayAlerts = true; //
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
MessageBox.Show("Excel file created/updated succcessfully");
}
At the first steps of the code a check for the Excel object, if it is already
running, is performed. If so, we do not create a new Excel object but we use the one that is running in the system. Then the workbook is properly created or updated. When saving it, it must be saved with
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared
in order to be able to reopen it and update it.
To speed up the data entering a modified code you may use is quoted.
You should add an additional button e.g. button9 and use the quoted code in the click event with the necessary modifications made for the button8 where you enter data.
Also, you have to declare the variables xlApp,xlWorkBook,xlWorkSheet etc to
be global and PUBLIC as in the following code,
............
public bool startd = false;
public int rownum;
public int MAX_ROWS = 30000;//You may define your own limit here
public bool isFirstTime = true;
public string oldBtnFileText;
public string oldBtnDataText;
public Microsoft.Office.Interop.Excel.Application xlApp;
public Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
public Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
public Microsoft.Office.Interop.Excel.Range range;
public object misValue;
private void button8_Click(object sender, EventArgs e)
{
if (startd == false)
{
return;
}
if (isFirstTime == true)
{
bool written = true;
int rnum = 1;
if (xlWorkSheet!=null)
{
range=xlWorkSheet.UsedRange;
while ((written) && (rnum < MAX_ROWS))
{
var test = (range.Cells[rnum, 1] as Microsoft.Office.Interop.Excel.Range).Value2;
if (test != null)
{
rnum++;
}
else
{
written = false;
}
}
if (written == false)
{
rownum = rnum;
isFirstTime = false;
}
else
{
MessageBox.Show("The current WorkSheet is Full");
return;
}
}
}
if (xlWorkSheet!=null)
{
xlWorkSheet.Cells[rownum, 1] = comboBox2.Text;
xlWorkSheet.Cells[rownum, 2] = textBox5.Text;
xlWorkSheet.Cells[rownum, 3] = textBox2.Text;
xlWorkSheet.Cells[rownum, 4] = comboBox3.Text;
xlWorkSheet.Cells[rownum, 5] = textBox3.Text;
xlWorkSheet.Cells[rownum, 6] = comboBox1.Text;
rownum++;
}
}
private void button9_Click(object sender, EventArgs e)
{
if (startd == false)
{
try
{
xlApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch (Exception ee)
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
}
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
try
{
xlWorkBook = xlApp.Workbooks.Open(#"cross_check.xls");//,
}
catch (Exception ex)
{
;//
}
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
oldBtnFileText = button9.Text.ToString();
button9.Text = "File Ready to accept data";
oldBtnDataText = button1.Text.ToString();
button8.Text = "Enter Data";
startd = true;
}
else
{
xlApp.DisplayAlerts = false;
xlWorkBook.SaveAs(#"cross_check.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, misValue, misValue, misValue, misValue, misValue);
xlApp.DisplayAlerts = true;
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
MessageBox.Show("Excel file created/updated succcessfully");
startd = false;
button9.Text = oldBtnFileText; //Restore the initial captions
button8.Text = oldBtnDataText;//...
}
}
//
Hope these can be useful.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I am making a Program to convert a csv( common selected value file) file into xls(microsoft excel file) file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConversionToXLSFile
{
public partial class Converter : System.Web.UI.Page
{
//Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
//xlWorkBook = xlApp.Workbooks.Add(misValue);
//xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
protected void Page_Load(object sender, EventArgs e)
{
//List<string> row = new List<string>();
string fullPath = #"D:\Work\Sep-14\ConversionToXLSFile\ConversionToXLSFile\File\diff_16122014095440.csv";
string[] fileRows = File.ReadAllLines(fullPath, Encoding.UTF8);
foreach (string rows in fileRows)
{
var columns = rows.Split(';');
for (int j = 0; j < fileRows.Length; j++)
{
for (int i = 0; i < columns.Length; i++)
{
List<string> elements = new List<string>();
foreach (string col in columns)
{
elements.Add(col);
xlWorkSheet.Cells[j, i] = col;
}
}
}
}
xlWorkBook.SaveAs("d:\\csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Console.WriteLine("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
private void Add(dynamic dynamic)
{
throw new NotImplementedException();
}
}
}
As far as I can see, you've commented out the code where you assign the variables xlApp, xlWorkBook and xlWorkSheet...
//Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
//xlWorkBook = xlApp.Workbooks.Add(misValue);
//xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Take the // out of each line and you won't get null reference exceptions when you try to use them.
I am Generating a Excel sheet from datatable dyanamically. I am able to add text into different cells as i needed. But i do not have any idea about how to add picture into a specified range..
Excel.Application oApp = new Excel.Application();
oApp.Application.Workbooks.Add(Type.Missing);
oApp.Range["B2", "C4"].Merge(Type.Missing);
Here i want to add picture..
I am trying like
System.Drawing.Image imgg = System.Drawing.Image.FromFile("c:\\D.jpg");
Now how could i add/copy my imgg into this range?? e.g.
App.Range["B2", "C4"]
You can get benefited with the following
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//add some text
xlWorkSheet.Cells[1, 1] = "Text1";
xlWorkSheet.Cells[2, 1] = "Text2";
xlWorkSheet.Shapes.AddPicture("C:\\sample.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45);
xlWorkBook.SaveAs("MyExcelFile.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
MessageBox.Show ("File created !");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
Have you tried giving position with excelpicture?
var picture = worksheet.Drawings.AddPicture("image_name", imgg);
picture.SetPosition(int row,int rowoffsetpixels,int column,int coloumoffsetpixels);//position for the image
You can add an image to your Excel spreadsheet quite easily (this assumes that you are using Microsoft.Office.Interop.Excel assembly reference, in C#) like this:
private Worksheet _xlSheet;
private Image _platypusLogo;
. . .
private void AddImage()
{
Clipboard.SetDataObject(_platypusLogo, true);
var cellRngImg = (Range)_xlSheet.Cells[IMAGE_ROW, IMAGE_COLUMN];
_xlSheet.Paste(cellRngImg, _platypusLogo);
}
Note that "IMAGE_ROW" and "IMAGE_COLUMN" are int constants or you can just use hard-coded ints, if you want to fly in the face of Steve McConnell's advice in Code Complete about constantifying all numbers other than sometimes 0 and 1
An image needs to be assigned to _platypusLogo. If you are using a C# utility app to dynamically generate the Excel spreadsheet, you could add a PictureBox control to a form, and then assign an image to it via its Image property (the control is named, by default, pictureBox1), and then assign it to the spreadsheet this way:
_platypusLogo = pictureBox1.Image;
Of course, you can assign to _platypusLogo directly/exclusively in code, too, if you prefer.
I managed to create an Excel file and tried to update the current system timings into first cell of the worksheet. But when the file is created, I get wrong values for timings. I want the current system time but it is displaying 12:00:00 However date is being displayed correctly.
I am using Microsoft Excel 12.0 Object Library. I need help to get the current system timings or need to reflect the timings as per the date time picker.
Here is my code:
namespace Test6attendance
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = DateTime.Now.Date.ToString("MM/dd/ yyyy, hh:mm:ss tt");
xlWorkBook.SaveAs("D:\\login.xlscsharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file D:\\csharp-Excel.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
It is because of the following line:
xlWorkSheet.Cells[1, 1] = DateTime.Now.Date.ToString("MM/dd/ yyyy, hh:mm:ss tt");
DateTime.Now.Date will set the time property to Midnight. Use this Instead
xlWorkSheet.Cells[1, 1] = DateTime.Now.ToString("MM/dd/ yyyy, hh:mm:ss tt");
Here is the DateTime.Now Property, DateTime.Date Property
I want to export datagrid information to excel file.My Problem is that i need to rewrite the same function in each windowsfrom that i want to export.
Is it possible to sent the datagrid information to Main function??
the code is:
private void button2_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for (i = 0; i <= dgvCostumers.RowCount - 1; i++)
{
for (j = 0; j <= dgvCostumers.ColumnCount - 1; j++)
{
DataGridViewCell cell = dgvCostumers[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
}
}
xlWorkBook.SaveAs(name + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\my documents\\" + name + ".xls");
textBox1.Text = "";
textBox1.Visible = false;
button1.Visible = true;
label2.Visible = false;
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
How about something like
private void DataGridViewToExcel(string name, DataGridView dgv)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for (i = 0; i <= dgv.RowCount - 1; i++)
{
for (j = 0; j <= dgv.ColumnCount - 1; j++)
{
DataGridViewCell cell = dgv[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
}
}
xlWorkBook.SaveAs(name + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
and then your button click code can change to something like
private void button2_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
DataGridViewToExcel(name, dgvCostumers);
MessageBox.Show("Excel file created , you can find the file c:\\my documents\\" + name + ".xls");
textBox1.Text = "";
textBox1.Visible = false;
button1.Visible = true;
label2.Visible = false;
}
}