C#实战007: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;

namespace ConsoleApplication3
{
    class EditExcel
    {
        /// <summary>
        /// 创建Excel并保存
        /// </summary>
        /// <param name="ExcelPath"></param>
        public void Create(string ExcelPath) 
        {
            //创建 Excel对象
            Application excel = new Application();
            //添加新工作簿
            Workbook newbook = excel.Workbooks.Add(true);
            //获取缺少的object类型值
            object missing = System.Reflection.Missing.Value;
            //向Excel文件中新增工作表
            newbook.Worksheets.Add(missing, missing, missing, missing);
            if (ExcelPath.EndsWith("\\"))//判断路径是否以“\”结尾
                //保存Excel文件
                newbook.SaveCopyAs(ExcelPath+"测试页面"+DateTime.Now.ToString("yyyymmddhhmmss")+".xls");
            else
                //保存Excel文件
                newbook.SaveCopyAs(ExcelPath+"\\"+""测试页面""+DateTime.Now.ToString("yyyymmddhhmmss") + ".xls");
            Console.WriteLine("Excel文件创建成功!");
            Console.ReadLine();
            //创建进程对象
            Process[] ExcelProcess =Process.GetProcessesByName("Excel");
            //关闭进程
            foreach (Process p in ExcelProcess)
            {
                p.Kill();
            }
        }
    }
}

在主函数中调用该函数即可实现该功能了,这里我用桌面路径测试的,生成的文件名是用时间拼接的,你也可以自定义文件名:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            //实例化该类
            EditExcel app = new EditExcel();
            //调用该方法并为其赋值
            app.Create(@"C:\Users\敏\Desktop");
        }
    }
   
}

猜你喜欢

转载自blog.csdn.net/kevinfan2011/article/details/83958207