C#创建Excel并保存

C#创建Excel并保存

需要添加Excel动态链接库引用。Microsoft.Office.Interop.Excel

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace CreateExcel
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        private void btn_create_click_Click(object sender, EventArgs e)
        {
            string P_str_Path = txt_path.Text;   //记录路径
            //创建Excel对象
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            //添加新工作簿
            if (excel == null)
            {
                Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
                return;
            }
            excel.Visible = true;
            Microsoft.Office.Interop.Excel.Workbook  WorkBook= excel.Application.Workbooks.Add(true);

            object missing = System.Reflection.Missing.Value;   //获取缺少的objext类型值
             WorkBook.Worksheets.Add(missing,missing,missing,missing);   //向excel添加工作表  
            if (P_str_Path.EndsWith("\\"))
                WorkBook.SaveCopyAs(P_str_Path + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls");
            else
                //保存Excel文件
                WorkBook.SaveCopyAs(P_str_Path + "\\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls");
            //弹出提示信息
            MessageBox.Show("Excel文件创建成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //创建进程对象
            System.Diagnostics.Process[] excelProcess = System.Diagnostics.Process.GetProcessesByName("EXCEL");
            foreach (System.Diagnostics.Process p in excelProcess)
                p.Kill();
        }

        private void btn_open_flo_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            folderBrowserDialog1.Description = "请选择保存输出图件的文件夹";
            folderBrowserDialog1.ShowNewFolderButton = true;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txt_path.Text = folderBrowserDialog1.SelectedPath;
            }

        }
    }
}

  

 

posted on 2015-12-29 21:24  h3iß3n  阅读(583)  评论(0)    收藏  举报

导航