C# 將excel表格嵌入到Word中
繼續開扒,今天要實現的是使用C#將excel表格嵌入到Word中這個功能,將word表格導入到excel中我已經寫過了,如有需要可參考我之前的文章,在開始前還有一點需要指出的是在我的這個示例中是將excel表格轉換為圖片,然后再嵌入至Word文檔中。
為了展示一下效果,我做了一個簡單的excel表格,請看源excel工作表截圖:
下面看看如何使用代碼:
第一步:新建一個Visual C#控制台項目,添加引用並使用如下命名空間:
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Xls;
第二步:創建一個ConvertExcelToImage(string excelFile)方法,將excel的工作表轉換為圖片。
static Image ConvertExcelToImage(string excelFile) { //創建一個excel workbook對象 Workbook workbook = new Workbook(); //加載excel文件 workbook.LoadFromFile(excelFile); //獲取第一個工作表 Worksheet sheet = workbook.Worksheets[0]; //獲取第一個工作表的最后一行 int lastRow = sheet.LastRow; //獲取第一個工作表的最后一列 int lastColumn = sheet.LastColumn; //將第一個工作表轉換為圖片 Image image = workbook.Worksheets[0].SaveToImage(1, 1, lastRow, lastColumn); return image; }
第三步:在主函數內,新建一個word文檔對象,並給它添加一個section和段落。
//新建一個word文檔 Document doc = new Document(); //添加一個section Section section = doc.AddSection(); //添加一個段落 Paragraph paragraph = section.AddParagraph();
第四步:獲取excel文件的路徑,新建一個DocPicture類的對象,調用ConvertExcelToImage()方法將excel工作表轉換為圖片並加載該圖片。
string excelfile = "Customers.xlsx"; //新建一個DocPicture類的對象 DocPicture pic = new DocPicture(doc); //將excel工作表轉換為圖片並加載 pic.LoadImage(ConvertExcelToImage(excelfile));
第五步:將圖片嵌入到Word文檔的段落中。
paragraph.AppendOleObject("Customers.xlsx", pic, Spire.Doc.Documents.OleObjectType.ExcelWorksheet);
第六步:保存文檔。
doc.SaveToFile("Output.docx", Spire.Doc.FileFormat.Docx);
嵌入到word文檔的效果圖:
全部代碼:
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Xls; namespace Embed_Excel_to_Word { class Program { static Image ConvertExcelToImage(string excelFile) { //創建一個excel workbook對象 Workbook workbook = new Workbook(); //加載excel文件 workbook.LoadFromFile(excelFile); //獲取第一個工作表 Worksheet sheet = workbook.Worksheets[0]; //獲取第一個工作表的最后一行 int lastRow = sheet.LastRow; //獲取第一個工作表的最后一列 int lastColumn = sheet.LastColumn; //將第一個工作表轉換為圖片 Image image = workbook.Worksheets[0].SaveToImage(1, 1, lastRow, lastColumn); return image; } static void Main(string[] args) { //新建一個word文檔 Document doc = new Document(); //添加一個section Section section = doc.AddSection(); //添加一個段落 Paragraph paragraph = section.AddParagraph(); //獲取excel文件的路徑 string excelfile = "Customers.xlsx"; //創建一個DocPicture類的對象pic DocPicture pic = new DocPicture(doc); //將excel工作表轉換為圖片並加載 pic.LoadImage(ConvertExcelToImage(excelfile)); //將圖片嵌入到word文檔中 paragraph.AppendOleObject("Customers.xlsx", pic, Spire.Doc.Documents.OleObjectType.ExcelWorksheet); //保存word文檔 doc.SaveToFile("Output.docx", Spire.Doc.FileFormat.Docx); } } }
總結:
需要注意的是E-iceblue的excel和word組件是兩個獨立的組件,一起使用會起沖突拋出異常,因此這里我使用的是Office組件,也就是添加office組件里的excel和word相關的dll文件作為引用。