在Excel中编辑嵌入Word文档中的Excel对象
本文关键字:Excel 文档 对象 Word 编辑 | 更新日期: 2023-09-27 18:25:54
我需要在Word文档中嵌入Excel文档。我使用了这个SO问题的答案->如何使用OpenXml 2.0将任何文件类型嵌入到Microsoft Word中;
一切都很好,除了:
DrawAspect = OVML.OleDrawAspectValues.Icon
允许您通过打开新的Excel实例来编辑Excel对象。但是,当我编辑数据时,它不会在Word文档中更新。
DrawAspect = OVML.OleDrawAspectValues.Content
允许您直接在Word文档中编辑Excel对象。
我的问题是,我必须在代码中更改什么,才能在新实例中编辑Excel对象,并使其正确反映在Word文档中?我想尽一切办法都无济于事。
告诉我,DrawAspect = OVML.OleDrawAspectValues.Icon
表明对象充当了一个图标,而更改不能正确地反映在这个图标中。
你可以试试我在这里按比例分配的方法:
如何使用OpenXML在书签后的WORD中插入图像
简而言之,使用OpenXMLSDK2.0生产力工具(它是OpenXMLSDk2.0的一部分)。在MSWord中手动执行任何需要处理文档的操作。然后在open XML SDK 2.0 Productivity Tool中打开此文件。然后找到您感兴趣的编辑,看看它是如何以OpenXML格式表示的,以及如何编程。
希望能有所帮助!
更新:
好吧,我现在好多了,问题是什么…所以除了我上面的建议,我建议你看看MSDN论坛上的这些帖子:
- 如何修改Word文档提供图表中嵌入的Excel数据
- word中嵌入的excel表格
我让自己转发代码样本(周在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;
}
}