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 e
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):
for (int i = 0; i < dataGridView1.RowCount; i++)
{
if (!dataGridView1.Rows[i].IsNewRow)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
MessageBox.Show(cell.FormattedValue.ToString());
}
}
}
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:
if (cell is DataGridViewComboBoxCell)
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.
private void ExportarDataGridViewExcel(DataGridView grd)
{
SaveFileDialog fichero = new SaveFileDialog();
fichero.Filter = "Excel (*.xls)|*.xls";
fichero.FileName = "export.xls";
if (fichero.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Application aplicacion;
Microsoft.Office.Interop.Excel.Workbook libros_trabajo;
Microsoft.Office.Interop.Excel.Worksheet hoja_trabajo;
aplicacion = new Microsoft.Office.Interop.Excel.Application();
libros_trabajo = aplicacion.Workbooks.Add();
hoja_trabajo =
(Microsoft.Office.Interop.Excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);
// changing the name of active sheet
hoja_trabajo.Name = "Exported from App";
// storing header part in Excel
for (int i = 1; i < grd.Columns.Count + 1; i++)
{
hoja_trabajo.Cells[1, i] = grd.Columns[i - 1].HeaderText;
}
//Recorremos el DataGridView rellenando la hoja de trabajo
for (int i = 1; i < grd.Rows.Count + 1; i++)
{
for (int j = 0; j < grd.Columns.Count; j++)
{
hoja_trabajo.Cells[i + 1, j + 1] = grd.Rows[i-1].Cells[j].Value.ToString();
}
}
libros_trabajo.SaveAs(fichero.FileName,
Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
libros_trabajo.Close(true);
aplicacion.Quit();
}
}
//in the click event of button1
private void button1_Click(object sender, EventArgs e)
{
ExportarDataGridViewExcel(dataGridView1);
}