空のExcelを新規作成して保存

10591 ワード

テスト用
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 Application = Microsoft.Office.Interop.Excel.Application;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace ExcelTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string fileName;
        Workbook workbook;
        object missing = Missing.Value; 
        Application app;

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                app = new Application()
                {
                    Visible = false
                };
                workbook = app.Workbooks.Add();
                fileName = System.Windows.Forms.Application.StartupPath + "\\excel.xlsx";
                SaveAsFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void SaveAsFile()
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new Exception("");
            }

            XlFileFormat fileFormat;
            if (String.Compare(Path.GetExtension(fileName).ToLower(), ".xlsx", false) == 0)
            {
                fileFormat = XlFileFormat.xlWorkbookDefault; //Excel 2007  
            }
            else
            {
                fileFormat = XlFileFormat.xlAddIn8;//Excel 2003  
            }

            try
            {
                //workbook.Save();
                workbook.SaveAs(fileName, fileFormat, missing, missing, missing, missing, XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
            }
            catch (Exception ex)
            {
               // ExceptionLog.Instance.WriteLog(ex, LogType.UI);
                throw;
            }
            finally
            {
                Dispose();
            }
        }

        private void Dispose()
        {
            int appHwnd = 0;
            try
            {
                if (workbook != null)
                {
                    workbook.Close(true, missing, missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                    workbook = null;
                }
                if (app != null)
                {
                    appHwnd = app.Hwnd;
                    app.Workbooks.Close();
                    app.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                    app = null;
                }
            }
            catch (Exception ex)
            {
                //ExceptionLog.Instance.WriteLog(ex, LogType.UI);
                throw ex;
            }
            GC.Collect();
            if (appHwnd > 0)
            {
                KillExcelProcess(appHwnd);
            }
        }


        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        private static void KillExcelProcess(int appHwnd)
        {
            Process[] ps = Process.GetProcesses();
            IntPtr t = new IntPtr(appHwnd); //
            int ExcelID = 0;
            GetWindowThreadProcessId(t, out ExcelID); // 
            foreach (Process p in ps)
            {
                if (p.ProcessName.ToLower().Equals("excel"))
                {
                    if (p.Id == ExcelID)
                    {
                        p.Kill();
                    }
                }
            }
        }
    }
}