简体   繁体   中英

How to embed an excel-file in a word-document using Microsoft.Interop.Word?

I have a problem that I have an Excel-table which I want to insert it into a Word-document, using Microsoft.Interop.Word .

I already tried this one:

var path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent?.FullName + @"\Documents\Businessprocess\Excel-Templates\Tabelle_zum_BP.xlsx";
var oIconLabel = "Tabelle zum BP";
var oMissing = System.Reflection.Missing.Value;
var oIconFileName = oMissing;
var oFileDesignInfo = path;
var oClassType = "Word.Document.8";

_wordDocument.Bookmarks["EPExcelFile"].Range.InlineShapes.AddOLEObject(
        oClassType, oFileDesignInfo, false, true, oIconFileName, oMissing, oIconLabel, oMissing);

I got this solution from an other thread on this website. The only problem is that it inserts the Excel-table now like this:

截图

How can I insert the table so that it is shown directly, and not over an icon?
I need a solution where the Excel-table is not linked to the Word-table, so that if I edit the Excel-table afterwards the one in the word should not be affected.

You can simply use the Range.PasteExcelTable method to achieve what you need:

var path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent?.FullName + @"\Documents\Businessprocess\Excel-Templates\Tabelle_zum_BP.xlsx";
var excel = (Excel.Application)new Excel.ApplicationClass() { Visible = true };
var template = excel.Workbooks.Add(path);
var worksheet = (Excel.Worksheet)template.Worksheets["__SHEET_NAME__"];
var table = (Excel.Range)worksheet.Range["__RANGE__"];

table.Copy();
_wordDocument.Bookmarks["EPExcelFile"].Range.PasteExcelTable(false, true, false);

In case you are wondering:

using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM