SoFunction
Updated on 2025-03-07

C# methods to create, read and modify Excel

// Namespaces, Variables, and Constants
using System;
using ;
using ;
private OleDbDataAdapter da;
private DataTable dt;
private void Excel_Load(object sender, e)
{
    // Create the DataAdapter.
    da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", ["ExcelConnectString1"]);
    // Create the insert command.
    String insertSql = "INSERT INTO [Sheet1$] (CategoryID, CategoryName, Description) VALUES (?, ?, ?)";
    = new OleDbCommand(insertSql, );
    ("@CategoryID", , 0, "CategoryID");
    ("@CategoryName", , 15, "CategoryName");
    ("@Description", , 100, "Description");
    // Create the update command.
    String updateSql = "UPDATE [Sheet1$] SET CategoryName=?, Description=? " WHERE CategoryID=?";
    = new OleDbCommand(updateSql, );
    ("@CategoryName", , 15, "CategoryName");
    ("@Description", , 100, "Description");
    ("@CategoryID", , 0, "CategoryID");
    // Fill the table from the Excel spreadsheet.
    dt = new DataTable( );
    (dt);
    // Define the primary key.
    = new DataColumn[] {[0]};
    // Records can only be inserted using this technique.
    = false;
    = true;
    = true;
    // Bind the default view of the table to the grid.
    = ;
}
private void updateButton_Click(object sender, e)
{
    (dt);
}