Embed an Excel worksheet in a Word document by Free API


I share a lot of documents (most are word documents and excel documents) with my clients. It makes sense to embed Excel worksheet in Word document, as which can avoid sending multiple documents. This article presents how to embed an Excel worksheet in Word document using a free library with C#.

Introduction

Often, I share a lot of documents (most are word documents and excel documents) with my clients. It makes sense to embed Excel worksheet in Word document, as which can avoid sending multiple documents. Fortunately, I found free apis(Spire.doc and Spire.xls) from CodePlex and they help me implement it. Here I want to share our solution with other guys may need it. It is worthy of note that my solution is to embed the whole data of Excel worksheet, rather than include a link to it, so can see worksheet's data visually.

Application Overview

In this solution, I am just going to go with blank word document because that's the simplest.
Now I first need to get an Excel worksheet and then convert it to an image by free spire.xls. Here I create a method for the section so that convenient for the following section of creating ole object in word document to call it.


public Image ConvertExcelToImage(string excelFile, ExcelVersion version)
{
//Create a new Excel document
Workbook workbook = new Workbook();
//Load an excel file
workbook.LoadFromFile(excelFile, version);
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Get the last row of worksheet
int lastRow = sheet.LastRow;
//Get the last column of worksheet
int lastColumn = sheet.LastColumn;
//Save the worksheet to Image
Image image= workbook.Worksheets[0].SaveToImage(1, 1, lastRow, lastColumn);
return image;
}

Original Excel worksheet:

excel

Next, I use free spire.doc to create blank word document and then embed the above Excel worksheet as ole object in it.

//Create a new Word document
Document doc = new Document();
//Add a new section
Section section = doc.AddSection();
//Add a new paragraph
Paragraph paragraph = section.AddParagraph();
//This is the file path of excel file
string excelfile = "..\\..\\DatatableSample.xls";
//Create a docPicture for word document
DocPicture pic = new DocPicture(doc);
//Convert image to docPicture
pic.LoadImage(ConvertExcelToImage(excelfile,ExcelVersion.Version97to2003));
//Add the ole object
paragraph.AppendOleObject(filepath,pic,Spire.Doc.Documents.OleObjectType.ExcelWorksheet);

//Save to word2007 document
doc.SaveToFile("Output.docx", Spire.Doc.FileFormat.Docx);

Output word document:

word


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: