Hello,
I have the following code that will export the entire DataBound DataGridView to Excel. Looking for advice on the best way to export only certain columns. Basically I want to have a new form open when a user clicks on a button that will give the user to select what they want to export. I think will use checkbox controls to select the items to export. Should I create new dataset and then export or is there way to filter the coumns in the current DataGridView?
Here is the code that I am using to export all columns to Excel.
using xl = Microsoft.Office.Interop.Excel;
private void button1_Click(object sender, EventArgs e)
{
xl._Application app = new Microsoft.Office.Interop.Excel.Application();
xl._Workbook workbook = app.Workbooks.Add(Type.Missing);
xl._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "User Detais";
for (int i = 1; i < dataGridViewResults.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridViewResults.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridViewResults.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridViewResults.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridViewResults.Rows[i].Cells[j].Value.ToString();
}
}
worksheet.Columns.AutoFit();
worksheet.Cells.HorizontalAlignment = xl.XlHAlign.xlHAlignLeft;
xl.Range rng = (xl.Range)worksheet.Rows[1];
rng.Font.Bold = true;
}