Silverlight 4でExcel連携するサンプル

2011.08.16

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Silverlight 4のCOMオートメーションを使ってエクセルを起動するサンプルを作ってみました。
データグリッドの内容をエクセルにして出力するするだけの簡単なものです。
以下がソースになります。

XAMLのソースです。

<UserControl x:Class="SampleExcel.MainPage"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	mc:Ignorable="d"
	d:DesignHeight="300" d:DesignWidth="400" 
	xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

	<Grid x:Name="LayoutRoot" Background="White">
		<Button Content="Excel" Height="23" HorizontalAlignment="Left"
				Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" 
				Width="75" Click="button1_Click" />
		<sdk:DataGrid AutoGenerateColumns="False" Height="150" 
				HorizontalAlignment="Left" Margin="12,41,0,0" 
				Name="dataGrid1" VerticalAlignment="Top" Width="310">
			<sdk:DataGrid.Columns>
				<sdk:DataGridTextColumn Header="ProductCd"
					Binding="{Binding ProductCd}" Width="100" />
				<sdk:DataGridTextColumn Header="Name"
					Binding="{Binding Name}" Width="100" />
				<sdk:DataGridTextColumn Header="Price"
					Binding="{Binding Price}" Width="100" />
			</sdk:DataGrid.Columns>
		</sdk:DataGrid>
	</Grid>
</UserControl>

次はC#のソースです。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Automation;
using System.Collections.ObjectModel;

namespace SampleExcel
{
	public partial class MainPage : UserControl
	{
		public MainPage()
		{
			InitializeComponent();

			var list = new List();
			list.Add(new Product{ProductCd = "a",Name = "item1",Price = 100 });
			list.Add(new Product{ProductCd = "b",Name = "item2",Price = 200 });
			list.Add(new Product{ProductCd = "c",Name = "item3",Price = 300 });
			dataGrid1.ItemsSource = list;
		}

		private void button1_Click(object sender, RoutedEventArgs e)
		{
			try{
				LaunchExcel();
			}catch(COMException ce){
				Console.WriteLine(ce);
			}catch (NotSupportedException ne){
				Console.WriteLine(ne);
			}
		}

		private void LaunchExcel()
		{
			var excel = AutomationFactory.
				CreateObject("Excel.Application");
			excel.Visible = true;

			dynamic workbook = excel.workbooks;
			workbook.Add();

			dynamic sheet = excel.ActiveSheet;
			dynamic cell = null;
			int i = 1;

			foreach (var data in dataGrid1.ItemsSource)
			{
				var product = data as Product;
				cell = sheet.Cells[i, 1];
				cell.Value = product.ProductCd;

				cell = sheet.Cells[i, 2];
				cell.Value = product.Name;

				cell = sheet.Cells[i, 3];
				cell.Value = product.Price;

				i++;
			}
		}
	}

	public class Product
	{
		public string ProductCd { get; set; }
		public string Name { get; set; }
		public int Price { get; set; }
	}
}

COMオートメーションを使うにはブラウザー外実行(Out of Browser)にする必要があります。
ブラウザ外実行にするにはSilverlightプロジェクトのプロパティを開いて「アプリケーションのブラウザー外実行を有効にする」にチェックを入れます。

次に「ブラウザー外実行の設定」ボタンを押下して設定画面を開いて、
「ブラウザー外実行での実行時に昇格された信頼を要求する」にチェックを入れます。

ビルドして実行します。ボタンを押すとエクセルが起動してデータグリッドの内容が出力されていたら成功です。