2015年2月3日火曜日

C#でExcel参照

ドラッグドロップするとシート1の(1,1)のセルの内容を表示してみる
あと、worksheetの名前をtextbox2の内容で更新してみる

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 System.IO;
using Microsoft.Office.Interop;

using Microsoft.Office.Interop.Excel;

namespace excelTest01
{
    public partial class Form1 : Form
    {
        Microsoft.Office.Interop.Excel.Application ExcelApp;
        Workbook Workbook;
        Worksheets Worksheets;
        Worksheet Worksheet;
        Range Range;
       
        public Form1()
        {
            InitializeComponent();

            ExcelApp = new Microsoft.Office.Interop.Excel.Application();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// ドロップ時イベント
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string[] filelist = (string[])e.Data.GetData(DataFormats.FileDrop);
            textBox1.Text =  Path.GetFileName(filelist[0]);
            string file = Path.GetFileName(filelist[0]);

            // excelを開く
            Workbook = ExcelApp.Workbooks.Open(filelist[0]);
            // Worksheet = Workbook.Sheets[1];    // ワークシートのインデックスは1から
            Worksheet = Workbook.Sheets[2];    // ワークシートのインデックスは1から
            Range = Worksheet.Cells[1, 1];
            textBox1.Text = Range.Text;
            Worksheet.Name = textBox2.Text;     // ワークシートのnameプロパティでワークシート名を変更出来るようだ

            // excelを閉じる
            ExcelApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp);
        }

        /// <summary>
        /// ドラッグエンター時イベント
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }
    }
}