0

I read excel file into datagridview and hanlde it(add row,update values,etc..) and when it's finish i want to update all data(include old and new data) into old excel file. Code below only update column"task"

 OleDbConnection MyConnection = new OleDbConnection(connString);
        MyConnection.Open();
        myCommand.Connection = MyConnection;
        sql = "Update into [Associates_Loading_Details$] values ('" + dataGridView1["Task", dataGridView1.CurrentRow.Index].Value.ToString() + "')";
        myCommand.CommandText = sql;
            myCommand.ExecuteNonQuery();
gggg
  • 25
  • 1
  • 9

1 Answers1

0

1) Delete excel file

File.Delete(pathOfExcel);

2) Download new file with the same name from DataGridView

    Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();   
    Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);   
    Microsoft.Office.Interop.Excel._Worksheet worksheet = null;  
    app.Visible = true;    
    worksheet = workbook.Sheets["Sheet1"];  
    worksheet = workbook.ActiveSheet;  
    worksheet.Name = "Any Name";  
    for (int i = 1; i < dataGridView1.Columns.Count + 1; i++) {  
        worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;  
    }   
    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) {  
        for (int j = 0; j < dataGridView1.Columns.Count; j++) {  
            worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();  
        }  
    }  
    workbook.SaveAs(excelPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
    app.Quit(); 
Imad
  • 7,126
  • 12
  • 55
  • 112
  • Thanks Imad I agree with you, but excel file has more one sheet and I much save all(other sheet don't update), so how can I do?Besides, sheet updated has format(color, header name,...) – gggg Oct 04 '17 at 03:39
  • If you want to retain the formatting, https://stackoverflow.com/questions/39210329/export-the-datagridview-to-excel-with-all-the-cells-format – Jeremy Thompson Oct 04 '17 at 03:59