我安装的是VS2005, Office2003,2009.01.12中午成功运行。ps: 必须保证电脑安装了excel。
首先,在解决方案资源管理器的引用文件夹右键“添加引用”,"COM"-Microsoft Excel 11.0 Object Library,这时回自动生成3个引用: Excel, Microsoft.Office.Core, VBIDE。
如图:
手工在前面添加using System.Reflection; 因为Missing.Value可能要用到很多次。最好不要添加excel的引用因为会引起混淆。
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace ExcelOutput
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
private void btnExcelOutput_Click(object sender, EventArgs e)
{
Excel.Application excel = new Excel.ApplicationClass();
try
{
Excel.Workbook book = excel.Workbooks.Add(Missing.Value); // 添加一个工作簿
Excel.Worksheet sheet = (Excel.Worksheet)excel.ActiveSheet;// 获取当前工作表
sheet.Name = "sheetName1"; // 修改工作表的名字
sheet.Cells[1, 1] = "333"; // 关键是,不管是Sheets[i]还是Cells[i,j]都是从1开始的,而不是从0开始的!!
excel.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
excel = null;
}
}
}
}
我花了2天时间老是出异常,原来是因为sheet.Cells[0, 0]不存在!! 下标是从1开始的