首先添加引用:
程序前面添加这个:
using Excel = Microsoft.Office.Interop.Excel;
代码:
Excel.Application _ExcelApp = null;
Excel.Workbook _WorkBook = null;
object missing = System.Reflection.Missing.Value;
_ExcelApp = new Excel.Application();
//string sFile = Application.StartupPath + "//example.xls";
string sFile = "D://Visual Studio 2005//Projects//ConsoleTest//ConsoleTest//bin//Debug//example.xls";
if (!System.IO.File.Exists(sFile))
{
Console.WriteLine("Excel文件不存在!", "错误");
Console.Read();
}
else
{
_WorkBook = _ExcelApp.Workbooks.Open(sFile, missing, true, missing, missing, missing
, missing, missing, missing, missing, missing, missing, missing, missing, missing);
_ExcelApp.Visible = true;
Excel.Worksheet _WorkSheet = (Excel.Worksheet)_WorkBook.ActiveSheet; //取得当前活动的Sheet
//_WorkSheet = (Excel.Worksheet)_WorkBook.Sheets["name"]; //取得指定名字的Sheet
Excel.Range range = _WorkSheet.get_Range("A1", "A1"); //指定范围,起始单元格,结束单元格
string num = "导入数值";
//num = range.Value2.ToString();
range.Value2 = num;
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
//range = null;
//关闭Excel进程
//if (_ExcelApp.DisplayAlerts == true || _WorkBook != null)
//{
// try
// {
// _WorkBook.Close(false, null, null);
// System.Runtime.InteropServices.Marshal.ReleaseComObject(_WorkBook);
// if (_ExcelApp != null)
// {
// _ExcelApp.DisplayAlerts = true;
// _ExcelApp.Workbooks.Close();
// _ExcelApp.Application.Quit();
// _ExcelApp.Quit();
// System.Runtime.InteropServices.Marshal.ReleaseComObject(_ExcelApp);
// _ExcelApp = null;
// }
// }
// catch (Exception ex)
// {
// if (ex.Message.ToString().Trim() != null)
// {
// System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("EXCEL");
// foreach (System.Diagnostics.Process process in processes)
// {
// if (process.MainWindowTitle.ToString().Trim() == "")
// {
// process.Kill();
// }
// }
// }
// }
//}
Console.WriteLine("导入成功");
Console.Read();
导入结果:
工作中参考别人的一段代码,那本书很厚,先记住一个简单的应用。