在Word中,Excel工作表(工作簿)被「包裝」在OLE控件中,該控件是InlineShapes
或Shapes
集合的成員。所以你需要你想使用的集合的AddOLEObject
方法。
訪問OLE服務器(Excel)的對象模型是通過InlineShape
或Shape
的OLEFormat
屬性。所以你的代碼會像下面的示例一樣。
請注意,雖然您說這是一個VSTO項目,但您向我們展示的代碼不是VSTO。您正在啓動Word.Application的新實例,但VSTO加載項將在進程中運行。我的代碼是VSTO代碼,但肯定可以調整的其他情形...
{
Word.Document doc = Globals.ThisAddIn.app.ActiveDocument;
object oRngTarget = Globals.ThisAddIn.app.Selection.Range;
//object oRngTarget = DocumentHelper.GetBookmark("test").Range;
object oOLEClass = "Excel.Sheet.12";
object oFalse = false;
Word.InlineShape ils = doc.InlineShapes.AddOLEObject(ref oOLEClass, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref oRngTarget);
Word.OLEFormat olef = ils.OLEFormat;
System.Globalization.CultureInfo oldCI= System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Excel.Workbook wb = (Excel.Workbook)olef.Object;
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
try
{
ws.get_Range("A1").Value2 = "New category";
ws.get_Range("B1").Value2 = 6.8;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Print(ex.Message);
}
finally
{
ws = null;
wb = null;
ils = null;
doc = null;
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}
}
要使用Word文檔中的表格以後的工作中,你基本上遵循同樣的原則:聲明和實例化一個InlineShape.OLEFormat
對象,激活它,然後抹上olef.Object
到Excel.Workbook:
olef.Activate();
Excel.Workbook wb = (Excel.Workbook)olef.Object;
輸入你自己試過的代碼片段。讓我們知道確切的要求,我們可以幫助您。總是縮小這個問題。請參閱[本](http://stackoverflow.com/help/mcve) – SSJGSS