我需要在Word文档中嵌入Excel文档。我在这个问题上使用了答案 - > How can I embed any file type into Microsoft Word using OpenXml 2.0;
一切正常,除了:
DrawAspect = OVML.OleDrawAspectValues.Icon
允许您通过打开新的Excel实例来编辑Excel对象。但是,当我编辑数据时,它不会在Word文档中更新。
DrawAspect = OVML.OleDrawAspectValues.Content
允许您直接在Word文档中编辑Excel对象。
我的问题是,我需要在代码中进行哪些更改,以便在新实例中编辑Excel对象并将其正确反映在Word文档中?我尝试了一切都无济于事。
有些东西告诉我,DrawAspect = OVML.OleDrawAspectValues.Icon
表示该对象充当图标,并且更改无法在此图标中正确反映。
答案 0 :(得分:4)
你可以试试我在这里骄傲的方式:
How to insert an Image in WORD after a bookmark using OpenXML。
简而言之,使用Open XML SDK 2.0 Productivity Tool(Open XML SDK 2.0的一部分)。在MS Word中手动执行文档操作。然后在Open XML SDK 2.0 Productivity Tool中打开此文件。然后找到您感兴趣的编辑内容,看看它是如何用OpenXML格式表示的,以及如何以编程方式表示。
希望有所帮助!
更新:
好的 - 我现在好了,问题是什么......所以除了上面的建议,我建议你在MSDN论坛上查看这个主题:
我让自己重新发布代码示例(由Ji Zhou在MSDN论坛上发布),以避免删除原始帖子。
希望从Word中检索Excel对象,更改一些单元格并将其嵌入Word中是有帮助的。
public static void Main()
{
using (WordprocessingDocument wDoc = WordprocessingDocument.Open(@"D:\test.docx", true))
{
Stream stream = wDoc.MainDocumentPart.ChartParts.First().EmbeddedPackagePart.GetStream();
using (SpreadsheetDocument ssDoc = SpreadsheetDocument.Open(stream, true))
{
WorkbookPart wbPart = ssDoc.WorkbookPart;
Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
Where(s => s.Name == "Sheet1").FirstOrDefault();
if (theSheet != null)
{
Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(theSheet.Id))).Worksheet;
Cell theCell = InsertCellInWorksheet("C", 2, ws);
theCell.CellValue = new CellValue("5");
theCell.DataType = new EnumValue<CellValues>(CellValues.Number);
ws.Save();
}
}
}
}
private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, Worksheet worksheet)
{
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
string cellReference = columnName + rowIndex;
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
}
else
{
row = new Row() { RowIndex = rowIndex };
sheetData.Append(row);
}
if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
{
return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
}
else
{
Cell refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
Cell newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
worksheet.Save();
return newCell;
}
}