代码一般可以直接copy使用,也许会在工程里面未引用,未引用的要自己添加引用(office com接口引用方式:右键工程→addreference→com页→Microsoft Excel xx.0 Object Library)。以下代码仅仅打开,给某个单元格设置颜色,然后关闭。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
namespace TestCsConsole
{
class Excel_Parser_Impl : IExcel_Parser
{
private Microsoft.Office.Interop.Excel.Application app = null;
private Microsoft.Office.Interop.Excel.Workbook wb = null;
private Microsoft.Office.Interop.Excel.Worksheet ws = null;
private Microsoft.Office.Interop.Excel.Range range = null;
private string filePath;
public bool LoadFile(string FileName)
{
filePath = FileName;
try
{
app = new Microsoft.Office.Interop.Excel.ApplicationClass();
wb = app.Workbooks.Open(filePath, false, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
app.Visible = false;
}
catch (System.Exception ex)
{
MessageBox.Show("Excel操作出错:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
finally
{
}
return true;
}
public void CloseFile()
{
wb.Save();
app.Quit();
app = null;
return;
}
public void SetCellColor(string TabSheetName, System.Drawing.Color CellColor, int Col, int Row)
{
if (true)
{
try
{
ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(TabSheetName);
range = (Range)ws.Cells[Row, Col];
range.Interior.Color = System.Drawing.ColorTranslator.ToOle(CellColor);
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
}
catch (System.Exception ex)
{
MessageBox.Show("Excel操作出错:" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
}
}
return;
}
}
}