文档星空最火知名网站>>Spire.Doc系列教程>>Word .NET库组件Spire.Doc系列教程(30): 在Word中导入Excel表格
Word .NET库组件Spire.Doc系列教程(30): 在Word中导入Excel表格
Spire.Doc for .NET是一个专业的Word .NET库,设计用于帮助开发人员高效地开发创建、阅读、编写、转换和打印任何来自.NET( C#, VB.NET, ASP.NET)平台的Word文档文件的功能。
本系列教程将为大家带来Spire.Doc for .NET在使用过程中的各类实际操作,本篇文章介绍了如何在Word中导入Excel表格以及如何在表格中插入图片。>>下载Spire.Doc最新试用版体验
C# 将 Excel 表格导入 Word
要将Excel表格显示在Word文档中,我们可以将Excel文档作为OLE对象插入Word,也可以将Excel表格复制到Word中。下面介绍如何将Excel表格复制到Word并保留Excel中的表格样式。
此方案需要在项目中同时引用Spire.Xls.dll和Spire.Doc.dll,请下载Spire.Office并使用其中的DLL文件。
static void Main(string[] args)
{
//创建Workbook对象
Workbook workbook = new Workbook();
//加载Excel文档
workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");
//获取第一个工作表
Worksheet sheet = workbook.Worksheets[0];
//创建Document对象,即Word文档
Document doc = new Document();
//在Word中添加表格
Table table = doc.AddSection().AddTable(true);
//根据Excel表格数据所占的行数和列数设置表格的行和列
table.ResetCells(sheet.LastRow, sheet.LastColumn);
//遍历Excel表格的行
for (int r = 1; r <= sheet.LastRow; r++)
{
//遍历Excel表格的列
for (int c = 1; c <= sheet.LastColumn; c++)
{
//获取Excel表格的单元格
CellRange xCell = sheet.Range[r, c];
//获取Word表格的单元格
TableCell wCell = table.Rows[r - 1].Cells[c - 1];
//将Excel单元格数据填充到对应的Word单元格
TextRange textRange = wCell.AddParagraph().AppendText(xCell.NumberText);
//复制单元格格式
CopyStyle(textRange, xCell, wCell);
}
}
//保存文档
doc.SaveToFile("result.docx", Spire.Doc.FileFormat.Docx);
}
////// 复制单元格格式
//////Word表格:单元格数据///Excel表格:单元格///Word表格:单元格private static void CopyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell)
{
//复制字体样式
wTextRange.CharacterFormat.TextColor = xCell.Style.Font.Color;
wTextRange.CharacterFormat.FontSize = (float)xCell.Style.Font.Size;
wTextRange.CharacterFormat.FontName = xCell.Style.Font.FontName;
wTextRange.CharacterFormat.Bold = xCell.Style.Font.IsBold;
wTextRange.CharacterFormat.Italic = xCell.Style.Font.IsItalic;
//复制单元格背景色
wCell.CellFormat.BackColor = xCell.Style.Color;
//复制文字对齐方式
switch (xCell.HorizontalAlignment)
{
case HorizontalAlignType.Left:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
break;
case HorizontalAlignType.Center:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
break;
case HorizontalAlignType.Right:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
break;
}
}
C# 在 word 表格中插入图片
Spire.Doc 提供 TableCollection 类,我们可以获取指定的表格,然后调用 DocPicture Paragraph.AppendPicture(Image image) 方法插入图片到单元格。
//创建一个document实例并加载示例文档
Document doc = new Document();
doc.LoadFromFile("Sample.docx");
//获取第一个table
Table table1 = (Table)doc.Sections[0].Tables[0];
//插入图片到表格并设置图片宽度和高度
DocPicture picture = table1.Rows[1].Cells[2].Paragraphs[0].AppendPicture(Image.FromFile("Logo.png"));
picture.Width = 110;
picture.Height = 90;
//保存文档
doc.SaveToFile("Result.docx", FileFormat.Docx);
*购买Spire.Doc正版授权的朋友可以点击哦~~


QQ交谈
在线咨询

渝公网安备
50010702500608号

客服热线