In my application I'm exporting DataGridView data to excel sheet now I want to pass the combobox and textbox selected values to excel sheet and I have to give title to my excel sheet as Report for my windows application how can I do that?
Can anyone help me on this?
I have code for exporting datagridview data to excel:
private void btnexcel_Click(object sender, EventArgs e)
{
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);
int i = 0;
int j = 0;
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
}
}
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");
}
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();
}
}
}
}
In the code where you take the
DataGridView
cell information the Value property is giving you the ValueMember for the comboBox cell rather than the DisplayMember in the comboBox. Instead you need to access the FormattedValue (which you can actually use for all your cells).Here is some code showing how to do this (along with some other small improvements):
There I just take the FormattedValue and display it with a MessageBox but for you you can simply assign it to your cell.
I've also used a slightly more compact syntax for the loops, and added in a check for the NewRow of the grid (which can contain null values which might break things).
Also, one useful thing to know is that once you have the cell, you can get the actual type of the cell like so:
And that gives you more options to work with when solving problems. As a final option you can even access the EditingControl (the actual DropDown in a ComboBoxColumn) and again this gives a lot more options.
You shouldn't need this in your case, but they are useful to know about.