首先右击项目添加引用,搜索Excel,添加结果中的Microsoft Excel xx.0 Object Library。
然后就可以像操作其他类库一样操作Excel对象了。
示例代码:
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
namespace ExcelCtrl
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private int row = 1;
private int col = 1;
private void Test_Click(object sender, EventArgs e)
{
Excel.Application excel = null;
try
{
excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
}
catch(System.Runtime.InteropServices.COMException ex)
{
Console.WriteLine(ex.Message);
}
if(excel == null)
{
excel = new Excel.Application();
}
excel.Visible = true;
Excel.Workbook activeWorkbook = null;
activeWorkbook = excel.ActiveWorkbook;
if(activeWorkbook == null)
{
excel.Workbooks.Add();
}
activeWorkbook = excel.ActiveWorkbook;
Excel.Worksheet activeWorksheet = null;
activeWorksheet = activeWorkbook.ActiveSheet;
activeWorksheet.Cells[row, col] = "Hello!";
System.Console.WriteLine(activeWorksheet.Cells[row, col].Value2.ToString());
row++;
col++;
}
}
}