1. 程式人生 > >【C#】C#刪除Excel整行,更新單元格內容

【C#】C#刪除Excel整行,更新單元格內容

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