append to excel file that is already created - c#

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.

Related

The Time value is not reflecting correctly in my excel worksheet

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

Export datagrid to Excel using Dialog Box on Winform

I'm looking for how to export a datagrid (or dataSet) (not datagridview) to Excel using dialog box which saves data in specific place, I am working on VS 2003 Winform not Webform.
This is my code:
I just need too open a dialog box to let the user choose where he wants to put his file:
private void button2_Click(object sender, System.EventArgs e)
{
#region
string data = null;
int i = 0;
int j = 0;
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dsSelectionListeDiffere.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= dsSelectionListeDiffere.Tables[0].Columns.Count - 1; j++)
{
data = dsSelectionListeDiffere.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
xlWorkBook.SaveAs("csharp.net-informations.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:\\csharp.net-informations.xls");
#endregion
}
and i have another code it works too :
#region
//// lblMessage.Visible = true;
//// lblMessage.Text = "";
// // Export all the details
// try
// {
// // Get the datatable to export
// DataTable dt = dsSelectionListeDiffere.Tables[0].Copy();
// dsSelectionListeDiffere = FrmFonctionPrincipale.getListeDifferesParClient(1);
// // Export all the details to Excel
//
//
// RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Win");
// objExport.ExportDetails(dt, Export.ExportFormat.Excel, "C:\\EmployeesInfo.xls");
// MessageBox.Show("Exporté Avec Succès dans C:\\EmployeesInfo.xls");
// }
// catch(Exception Ex)
// {
// MessageBox.Show(Ex.Message);
//// lblMessage.Text = Ex.Message;
// }
#endregion
If you don't need to change the filename, but only the folder where this file is saved, then you can use the FolderBrowserDialog to ask just the folder where the file will be saved
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Select the destination folder";
fbd.ShowNewFolderButton = true;
fbd.RootFolder = Environment.SpecialFolder.Personal;
if( fbd.ShowDialog() == DialogResult.OK )
{
string folderName = fbd.SelectedPath;
.... the rest of your excel export code .....
// Pass the full path to the SaveAs method
string fullPathName = Path.Combine(folderName, "csharp.net-informations.xls");
xlWorkBook.SaveAs(fullPathName, .....);
.....
MessageBox.Show("Excel file created , you can find the file in: " + fullPathName);
}
If you need to change also the file name, then you need to use a SaveFileDialog instance.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*" ;
sfd.FilterIndex = 1 ;
sfd.RestoreDirectory = true ;
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if(sfd.ShowDialog() == DialogResult.OK)
{
if(sfd.FileName.Length > 0)
{
... the rest of your excel code here ....
// sfd.FileName already contains the full path so
xlWorkBook.SaveAs(sfd.FileName, .....);
}
}
else
{
if(MessageBox.Show("Are you sure you want to quit without saving?", "Quitting",
MessageBoxButtons.YesNo) == DialogResult.No)
{
// This important to stop the Form to close if this button is the Cancel/AcceptButton
// or its property DialogResult is not DialogResult.None
this.DialogResult = DialogResult.None;
}
}

Copy data from datagrid to Excel and open the file without saving it

I'm working on VS 2003 C# WINFORM.
I want where I click the button, the datagrid (not datagridView) will be copied in the Excel file and it will be opened (with data of course) then the user will choose if he want to save it after the analyse or not.
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*" ;
sfd.FilterIndex = 1 ;
sfd.RestoreDirectory = true ;
sfd.Title = "Liste des différés";
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if(sfd.ShowDialog() == DialogResult.OK)
{
if(sfd.FileName.Length > 0)
{
string data = null;
int i = 0;
int j = 0;
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dsSelectionListeDiffere.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= dsSelectionListeDiffere.Tables[0].Columns.Count - 1; j++)
{
data = dsSelectionListeDiffere.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
// Pass the full path to the SaveAs method
// string fullPathName = Path.Combine(folderName, "csharp.xls");
xlWorkBook.SaveAs(sfd.FileNames, 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);
}
}
}
catch(Exception ex )
{
MessageBox.Show(ex.Message);
}
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();
}
}

Excel worksheet change event is not firing

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;
}
}
}

How To send datagrid in function

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;
}
}

Categories