提问
我需要在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建议该对象充当Icon,并且更改不能正确反映在此Icon中.
最佳答案
您可以尝试我在这里推荐的方法:How to insert an Image in WORD after a bookmark using OpenXML.
简而言之,请使用Open XML SDK 2.0生产率工具(它是Open XML SDK 2.0的一部分).在MS Word中手动执行文档处理所需的任何操作.然后在“ Open XML SDK 2.0生产率工具”中打开此文件.然后找到您感兴趣的编辑,以查看它如何以OpenXML格式表示以及如何以编程方式进行编辑.
希望有帮助!
更新:
好的-现在我已经好了,问题是…所以除了上面的建议外,我建议您在MSDN论坛上查看以下线程:
> How to modify the imbedded Excel in a Word document supplying chart
data
> Embedded excel sheet in word
我让自己重新发布代码示例(由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;
}
}