如何使用c#将数据从datagridview更新到excel

时间:2017-10-04 03:22:57

标签: c# excel vsto

我将excel文件读入datagridview并对其进行处理(添加行,更新值等等),当它完成后我想将所有数据(包括旧数据和新数据)更新为旧的excel文件。 以下代码仅更新列"任务"

 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();

1 个答案:

答案 0 :(得分:0)

1)删除excel文件

File.Delete(pathOfExcel);

2)从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();