Winfrom操作EXCEL

第一步配置管理器

//调用打开后的Excel
DataTable dt = OpenExcel();
string strMessage = dt.Rows[3][2].ToString();
//打开Excel
public DataTable OpenExcel()
{
    string strPath = @"system/setup/part_list.xls";
    try
    {
        string strConn;
        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
        OleDbConnection OleConn = new OleDbConnection(strConn);
        OleConn.Open();
        String sql = "SELECT * FROM  [Sheet1$]";//可是更改Sheet名称,比如sheet2,等等

        OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
        DataSet OleDsExcle = new DataSet();
        OleDaExcel.Fill(OleDsExcle, "Sheet1");
        OleConn.Close();

        return OleDsExcle.Tables["Sheet1"];
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过以下步骤在 WinForm 中修改 Excel 文件: 1. 在 Visual Studio 中创建 WinForm 应用程序。 2. 在界面中添加一个 Button 控件和一个 DataGridView 控件。 3. 在 Button 的 Click 事件中添加以下代码: ``` private void button1_Click(object sender, EventArgs e) { // 打开文件对话框选择 Excel 文件 OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Excel 文件|*.xls;*.xlsx"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { // 获取 Excel 文件路径 string filePath = openFileDialog1.FileName; // 连接 Excel 数据源 string connectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; OleDbConnection connection = new OleDbConnection(connectionString); connection.Open(); // 读取 Excel 数据 OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); // 在 DataGridView 控件中显示数据 dataGridView1.DataSource = dataTable; // 修改数据 dataTable.Rows[0]["Column1"] = "New Value"; dataTable.Rows[1]["Column2"] = "Another New Value"; // 更新 Excel 数据 OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter); adapter.Update(dataTable); // 关闭连接 connection.Close(); } } ``` 这样,当用户点击 Button 控件时,就会打开文件对话框,让用户选择 Excel 文件,并将文件中的数据显示在 DataGridView 控件中。然后,你可以通过修改 DataTable 中的数据来更新 Excel 文件中的数据。最后,使用 OleDbDataAdapter 的 Update 方法将修改后的数据写回 Excel 文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值