做法:
1,先添加引用COM,找 Excel
2,using Excel = Microsoft.Office.Interop.Excel;
3,
代码
private Excel.Application m_objExcel = null;
private Excel.Workbooks m_objBooks = null;
private Excel._Workbook m_objBook = null;
private Excel.Sheets m_objSheets = null;
private Excel._Worksheet m_objSheet = null;
private Excel.Range m_objRange = null;
private object m_objOpt = System.Reflection.Missing.Value;
private void button3_Click(object sender, EventArgs e)
{
m_objExcel = new Excel.Application();
m_objExcel.Visible = false;
m_objExcel.DisplayAlerts = false;
if (m_objExcel.Version != "11.0")
{
MessageBox.Show("您的 Excel 版本不是 11.0 (Office 2003),操作可能会出现问题。");
m_objExcel.Quit();
return;
}
m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
m_objBook = m_objBooks.Open(@"E:WebSite2Book2.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
m_objRange = m_objSheet.get_Range("B3", m_objOpt);
m_objRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlDiagonalDown].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
m_objRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlDiagonalUp].LineStyle = Excel.XlLineStyle.xlContinuous;
m_objRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlDiagonalUp].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
m_objRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
m_objRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
m_objRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
m_objRange.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlLineStyleNone;
m_objBook.Save();
m_objBook.Close(false, m_objOpt, m_objOpt);
m_objExcel.Quit();
this.DisposeExcel();
}
/// <summary>
/// 释放所引用的COM对象。注意:这个过程一定要执行。
/// </summary>
public void DisposeExcel()
{
ReleaseObj(m_objSheets);
ReleaseObj(m_objBook);
ReleaseObj(m_objBooks);
ReleaseObj(m_objExcel);
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
private void ReleaseObj(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch { }
finally { o = null; }
}