C#でExcelファイルを読み書きするためには、まず以下の2つの準備が必要です。
- Microsoft Office (Excel)のインストール
- Visual Studioから「参照の追加」=> 「COM」タブからMicrosoft Excel 11 Object Libraryを追加(COMのバージョン部分は、インストールしたOfficeのバージョンに依存します)
サンプルコード
以下は、実際にExcelファイルを開いて、Cellへの読み書き、sheetの追加を行うサンプルコードです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
namespace Example
{
class ExcelExample
{
private static void RunExcelExample()
{
Excel.Workbook book = null;
Excel.Application excel = null;
try
{
excel = new Excel.Application();
book = excel.Workbooks.Open(@"c:\test.xls",
Type.Missing,
true,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing
);
// read
Excel.Worksheet sheet = (Excel.Worksheet)book.Sheets["Sheet1"];
for (int i = 1; i < 10; i++)
{
object val = ((Excel.Range)sheet.Cells[1, i]).Value2;
Console.WriteLine(val);
}
// add new work sheet and write values to cells
Excel.Workbook workbook = excel.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet sheet = (Excel.Worksheet)workbook.ActiveSheet;
((Excel.Range)sheet.Cells[1, 1]).Value2 = 1000;
((Excel.Range)sheet.Cells[2, 2]).Value2 = "String";
excel.Visible = true;
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
finally
{
if (book != null)
{
book.Close(false, Type.Missing, Type.Missing);
}
}
}
}
}
コメント