【C#】C#删除Excel整行,更新单元格内容

这篇博客介绍如何使用C#与Microsoft Office Interop Excel库来删除Excel文件中的整行,并更新特定单元格的内容。通过创建Excel Application实例,打开工作簿,遍历工作表,设置编辑范围,调用Delete方法删除行,然后修改指定位置的单元格值,最后保存更改并关闭工作簿。
</pre><pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;

namespace DelExcel
{
    public partial class Form1 : Form
    {
        private Excel._Application excelApp = null;
        private Excel.Workbook book = null;
        private Excel.Worksheet sheet = null;
        private Excel.Range range = null;
        string filePath = @"E:\2010.xls";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            delExcel(filePath);
        }

        private void delExcel(string filePath)
        {
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            excelApp.Visible = false;

            book = excelApp.Workbooks.Open(filePath, Missing.Value, false, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            int wsCount = book.Worksheets.Count;
            for (int i = 1; i <= wsCount; i++)
            {
                sheet = (Excel.Worksheet)book.Worksheets[i];
                //获取编辑范围
                range = (Excel.Range)sheet.Rows[1, Missing.Value];
                //删除整行
                range.Delete(Excel.XlDirection.xlDown);
                
                //更新单元格内容
                sheet.Cells[1, 3] = "pcID";

                //保存编辑
                book.Save();
            }
            //关闭book
            book.Close(Missing.Value, Missing.Value, Missing.Value);
            //退出excel application,可以将前面的excelApp.Visible = false改为excelApp.Visible = true看看;
            excelApp.Workbooks.Close();
            excelApp.Quit();        
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值