jn1*_*1kk 3 c# excel interop ms-word openxml
我需要将 Excel 文档嵌入到 Word 文档中。我使用了这个问题的答案 -> 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该对象充当图标,并且更改无法正确反映在该图标中。
你可以尝试我在这里提出的方法:
如何使用 OpenXML 在 WORD 中的书签后插入图像。
简而言之,使用 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4599 次 |
| 最近记录: |