1. 程式人生 > >C#實戰008:Excel操作-建立新的Excel工作表

C#實戰008:Excel操作-建立新的Excel工作表

接下來我們接著新建Excel工作表,在新建Excel檔案基礎上新增工作表。

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 建立工作表
        /// <summary>
        /// 建立新的工作表
        /// </summary>
        /// <param name="ExcelName"></param>
        public void CreateSheet(string ExcelName)
        {
            //建立 Excel物件
            Application App = new Application();
            //獲取缺少的object型別值
            object missing = Missing.Value;
            //開啟指定的Excel檔案
            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);
            //Add引數(Before, After, Count, Type);
            Console.WriteLine("請輸入需要新增的工作表名稱:");
            string sheetName = Console.ReadLine();
            newsheet.Name = sheetName;
            Console.WriteLine("新增成功!");
            App.DisplayAlerts = false;//不現實提示對話方塊
            openwb.Save();//儲存工作表
            App.Visible = true;//顯示Excel
            openwb.Close(false, missing, missing);//關閉工作表
            //建立程序物件
            Process[] ExcelProcess = Process.GetProcessesByName("Excel");
            //關閉程序
            foreach (Process p in ExcelProcess)
            {
                p.Kill();
            }
        }
        #endregion
    }
}

Add後面的引數(Before, After, Count, Type)解釋:

Before:在其他工作前面新增工作表

After:在其他工作後面新增工作表

Count:要新增幾個工作表

Type:工作表的型別

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

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            EditExcel app = new EditExcel();
            //app.Create(@"C:\Users\敏\Desktop");
            app.CreateSheet(@"C:\Users\敏\Desktop\測試頁面20181211021229.xls");
        }
    }
   
}

我現在使用控制檯寫的,所以直接給其賦值絕對路徑了,如果你用windows視窗可以動態獲取檔案路徑。