Hi Guys.. Can any experts in Excel/C# Help me with this one? I think I'm nearly there.
Currently I have a DGV on a windows form which pulls data from a Datasource. I want to export the findings to and Excel report template.
I've managed to export the data into Excel (with some help from the web and of course Dani). However, I'm trying to format it so that the data in question is populated into selective cells of my choosing i.e. They fit the template.
My 'Export' Code currently looks like this...
private void button1_Click(object sender, EventArgs e)
{
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Open("E:\\boyce[TEMPLATE].xls", Editable: true);
Excel.Worksheet ws = (Excel.Worksheet)workbook.Worksheets[1];
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
ws = workbook.Sheets["Sheet1"];
ws = workbook.ActiveSheet;
// changing the name of active sheet
ws.Name = "Exported from gridview";
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView2.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
ws.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
}
}
}
I have attached 3 Screenshots also. 1 showing the DGV, 1 of the Template Report and the final one showing how data it currently being pulled across.
My FOR Statements really need some work and this is one area I'm not great at.
Any Advice/Help to get this data formatted correctly would be great.
Regards
Mark.