I am trying to export my datagridview contents to a excel file which exist in application.startuppath
. The problem I am facing is that whenever I export my grid content to excel, it overwrites the previous content. What I would like to do is append to my excel file and not overwrite my existing content.
Here is my code:
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Open(Application.StartupPath+"excelfile.xls");
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
else
worksheet.Cells[i + 2, j + 1] = "";
}
}
workbook.Close(SaveChanges: true);
app.Quit();
EDIT: Updated code : thanks to @Alex Bell
int _offset = worksheet.UsedRange.Rows.Count;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 1; j < dataGridView1.Columns.Count; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
worksheet.Cells[i + 2 + _offset, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
else
worksheet.Cells[i + 2 + _offset, j + 1] = "";
}
}
Resolved my problem of appending data but another small problem is every time I update it leaves a blank row between old rows and new rows.