1. 程式人生 > >C#實戰014:Excel操作-獲取Excel工作表明細

C#實戰014:Excel操作-獲取Excel工作表明細

          昨天新增工作表時忽略了一個問題,那就是當你所建的表已經存在時程式就報錯了,所以這裡我們先獲取sheet工作表明細,然後進行比對,當沒有時建立,有則跳過。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.Reflection;

namespace ConsoleApplication3
{
    class EditExcel
    {
        #region 獲取Excel工作表
        /// <summary>
        /// 獲取Excel工作表
        /// </summary>
        /// <param name="ExcelName"></param>
        public void compute(string ExcelName)
        {
            List<string> sheets = new List<string>(); //儲存Excel中的sheet工作表
            Application App = new Application();       //建立 Excel物件
            object missing = Missing.Value;            //獲取缺少的object型別值
            Workbook openwb = App.Workbooks.Open(ExcelName, missing, missing, missing, missing,
                missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);    //開啟指定的Excel檔案
            Worksheet newsheet = (Worksheet)openwb.Worksheets.Add(missing, missing, 1, missing);     //新增新的Excel工作表
            for (int i = 1; i < openwb.Worksheets.Count; i++)   //迴圈sheet工作表
            {
                string sheet =( (Worksheet)openwb.Worksheets[i]).Name; 
                Console.WriteLine(sheet);  //列印sheets列表
                sheets.Add(sheet);   //將Excel工作表存入sheets陣列中
            }
            Console.ReadLine();
        }
        #endregion
    }
}