小Q的博客

  • 首页
  • net编程
    • 产品和框架
    • 开发实例
    • 经验技巧
    • 开源组件
  • wp独立站
  • 自媒体
  • 日记本
  • 工具箱
每个程序员,都应该有一个自己的博客站
  1. 首页
  2. net编程
  3. 经验技巧
  4. 正文

c#中使用Aspose.Word组件,将数据和图片导出至Word

2022年12月5日 1332点热度 2人点赞 0条评论

上一篇分享的是导出Excel的示例,今天分享将数据导出至Word,以及如何读取Word文档中的图片。用的组件包括2个,分别是Aspose.Word和Spire.Doc。这2个组件,都可以从Nuget中下载获取,而且最低支持Net4.6的。我们通过几个示例实现导出至Word
cover

目录

  • 示例1、Word文档中插入图片
  • 示例2、从Word文档中获取图片
  • 示例3、DataTable数据导出Word
  • 示例4、书签方式导出Word
  • 示例5、含图片的列表数据导出Word

示例1、Word文档中插入图片

这是将图片插入到已经存在的Word文档里,图片和文字如何布局可以代码控制。用的是Spire.Doc组件

string folder = SystemHelper.GetSystemPath(SystemFolderName.Desktop);
string wordFile = folder + @"\tempfile\testWord.docx";

//实例化一个Document对象           
Spire.Doc.Document doc = new Spire.Doc.Document();
doc.LoadFromFile(wordFile);

//添加section和段落           
Spire.Doc.Section section = doc.AddSection();
section.AddParagraph();

//加载图片到System.Drawing.Image对象,
//使用AppendPicture方法将图片插入到段落
string imageFile = folder + @"\tempfile\liveplat.jpg";
Image image = Image.FromFile(imageFile);
Spire.Doc.Fields.DocPicture picture = doc.Sections[0].Paragraphs[0].AppendPicture(image);

//设置文字环绕方式           
picture.TextWrappingStyle = Spire.Doc.Documents.TextWrappingStyle.Square;

//指定图片位置
picture.HorizontalPosition = 10f;
picture.VerticalPosition = 10f;

//设置图片大小          
picture.Width = 200;
picture.Height = 200;

//保存到文档          
doc.SaveToFile(folder + @"\tempfile\testWord-res.doc", Spire.Doc.FileFormat.Doc);

 

效果图

文档中插入图片

示例2、从Word文档中获取图片

这里是从Word文档中读取图片,其实就是循环遍历文档中的对象,找到是Image的就获取。用的也是Spire.Doc组件

//初始化一个Document实例并加载Word文档           
string folder = SystemHelper.GetSystemPath(SystemFolderName.Desktop);
string wordFile = folder + @"\tempfile\testWord-res.doc";
Spire.Doc.Document doc = new Spire.Doc.Document();
doc.LoadFromFile(wordFile);

//遍历Word文档中每一个section
int index = 0;
foreach (Spire.Doc.Section section in doc.Sections)
{
    //遍历section中的每个段落               
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        //遍历段落中的每个DocumentObject                   
        foreach (Spire.Doc.DocumentObject docObject in paragraph.ChildObjects)
        {
            //判断DocumentObject是否为图片                       
            if (docObject.DocumentObjectType == DocumentObjectType.Picture)
            {
                //保存图片到指定路径并设置图片格式 
                DocPicture picture = docObject as DocPicture;
                String imageFile = folder + @"\tempfile\" + String.Format("Image-{0}.jpg", index);

                picture.Image.Save(imageFile, System.Drawing.Imaging.ImageFormat.Png);
                index++;
            }
        }
    }
}

示例3、DataTable数据导出Word

从这个示例开始,用的是Aspose.Word组件。个人感觉2个组件差不多,都不错。凭你喜欢使用吧,Spire.Doc组件有个好处,就是提供Winform下在预览功能。

DataTable tblDatas = new DataTable();
tblDatas.Columns.Add("序号", Type.GetType("System.Int32"));
tblDatas.Columns.Add("姓名", Type.GetType("System.String"));
tblDatas.Columns.Add("性别", Type.GetType("System.String"));
tblDatas.Columns.Add("分值", Type.GetType("System.String"));
tblDatas.Rows.Add(1, "张三", "男", "89");
tblDatas.Rows.Add(2, "李四", "男", "83");
tblDatas.Rows.Add(3, "王五", "男", "89");
tblDatas.Rows.Add(4, "老六", "女", "87");
tblDatas.Rows.Add(5, "小红", "女", "99");

//DataTable方式导入
string wordFile3 = folder + @"\tempfile\testWord3-res.docx";
AsposeWordHelper.SaveDataTable(wordFile3, tblDatas);

效果图

datatable导出

示例4、书签方式导出Word

Word书签在插入的面板里,如果想显示书签,在选项->高级->显示文档内容结点里,勾上就行了。这个插入方式感觉很好用,相当于精准定位,推荐使用。而且不光能插入文字,还能插入图片

word中显示书签

//书签方式导出
//显示书签,在选项-高级设置里
Dictionary<string, object> dicBm = new Dictionary<string, object>();
dicBm.Add("title", "测试标题1111");
dicBm.Add("table", tblDatas);
dicBm.Add("count", tblDatas.Rows.Count);

Image image = Image.FromFile(folder + @"\tempfile\liveplat.jpg");
dicBm.Add("image1", image);

dicBm.Add("colName", "姓名123456");
dicBm.Add("colAge", "40");
dicBm.Add("colHeight", "165cm");
Image image2 = UrlHelper.DownloadImage(@"https://navisoft.oss-cn-hangzhou.aliyuncs.com/tempfile/testface2.png");
dicBm.Add("colImage", image2);

string wordFile4 = folder + @"\tempfile\testWord4.docx";
string wordFile42 = folder + @"\tempfile\testWord4-res.docx";
AsposeWordHelper.SaveBookMark(wordFile4, wordFile42, dicBm);

示例5、含图片的列表数据导出Word

这是最综合的一个示例,列表数据,里面包含图片字段,还涉及了单元格的合并。适合导出销售或采购订单明细,带图片那种。Aspose.Word组件还能插入图表组件,功能是非常强大的

//实例化一个新的Word Document

//也可以在Aspose.Words.Document doc = newAspose.Words.Document(path)中加path参数,

//此path指向你设计好的Word模板路径
Aspose.Words.Document doc = new Aspose.Words.Document();
Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);

//设置单元格内容对齐方式
builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;

//清除设置
builder.PageSetup.ClearFormatting();

DataTable tbl = new DataTable();// m_db.GetDataTable(sql, m_cn);
tbl.Columns.Add("XZ", typeof(int));
tbl.Columns.Add("ZPPATH", typeof(string));
tbl.Columns.Add("XM", typeof(string));
tbl.Columns.Add("SZDW", typeof(string));
tbl.Columns.Add("DWDH", typeof(string));
tbl.Columns.Add("SJHM", typeof(string));
tbl.Columns.Add("DWYB", typeof(string));
tbl.Columns.Add("DZYJ", typeof(string));

tbl.Rows.Add(1, @"https://navisoft.oss-cn-hangzhou.aliyuncs.com/tempfile/testface2.png", "geovindu", "缔友计算机信息技术有限公司;软件工程师", "82397501", "13824350518", "518003", "463588883@qq.com");
tbl.Rows.Add(2, @"https://navisoft.oss-cn-hangzhou.aliyuncs.com/tempfile/testface2.png", "涂年生", "缔创智能工程技术有限公司;网络工程师", "82397502", "13824350518", "518003", "geovindu@qq.com");
tbl.Rows.Add(3, @"https://navisoft.oss-cn-hangzhou.aliyuncs.com/tempfile/testface2.png", "涂聚文", "缔建智能建筑工程有限公司;UI设计师", "82397503", "13824350518", "518003", "463588883@qq.com");


List<string> list = new List<string>();

if (tbl != null && tbl.Rows.Count > 0)
{
    //加载小组
    for (int i = 0; i < tbl.Rows.Count; i++)
    {
        if (!list.Contains(tbl.Rows[i]["XZ"].ToString()))
        {
            list.Add(tbl.Rows[i]["XZ"].ToString());
        }
    }

    double imgcellwidth = 85;
    double imgcellheight = 120;
    double cellwidth = 165;
    double cellheight = 18.5;

    //匹配小组中的学员
    builder.StartTable();//开始画Table            
    builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center; // RowAlignment.Center;                

    string xz = string.Empty;
    int count = 0;
    int rowcount = 0;
    for (int n = 0; n < list.Count; n++)
    {
        xz = list[n];
        builder.RowFormat.Height = 20;
        //插入Table单元格

        builder.InsertCell();

        //Table单元格边框线样式
        builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;

        //Table此单元格宽度
        builder.CellFormat.Width = 500;

        //此单元格中内容垂直对齐方式
        builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;

        builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
        builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;

        //字体大小
        builder.Font.Size = 11;

        //是否加粗
        builder.Bold = true;

        //向此单元格中添加内容
        builder.Write(xz);

        //Table行结束
        builder.EndRow();
        builder.Bold = false;
        DataRow[] rows = tbl.Select("xz='" + xz + "'");
        for (int i = 0; i < rows.Length; i = i + 2)
        {
            count++;
            rowcount = (count - 1) * 6 + 1 + n;
            //第一行
            builder.InsertCell();
            builder.RowFormat.Height = imgcellheight;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;

            //合并行单元格
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;

            builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;
            builder.CellFormat.TopPadding = 2;
            builder.CellFormat.WrapText = false;
            builder.CellFormat.Width = imgcellwidth;

            if (!string.IsNullOrEmpty(rows[i]["ZPPATH"].ToString()))
            {
                //向此单元格中插入图片
                Aspose.Words.Drawing.Shape shape = new Aspose.Words.Drawing.Shape(doc, Aspose.Words.Drawing.ShapeType.Image);

                //string url = System.Configuration.ConfigurationManager.AppSettings["UserPhotosSitePath"] + "\\" + rows[i]["ZPPATH"].ToString();
                string url = @"https://navisoft.oss-cn-hangzhou.aliyuncs.com/tempfile/testface2.png";
                shape.ImageData.SetImage(url);

                shape.Width = imgcellwidth - 2;
                shape.Height = imgcellheight;
                shape.HorizontalAlignment = Aspose.Words.Drawing.HorizontalAlignment.Center;
                Aspose.Words.CompositeNode node = shape.ParentNode;

                //把此图片移动到那个单元格中
                builder.MoveToCell(0, rowcount, 0, 0);
                builder.InsertNode(shape);
            }

            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.Width = cellwidth;
            builder.Write(rows[i]["XM"].ToString()); //

            builder.InsertCell();
            builder.RowFormat.Height = imgcellheight;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;

            //合并行单元格
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
            builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;
            builder.CellFormat.Width = imgcellwidth;
            if (rows.Length > i + 1)
            {
                if (!string.IsNullOrEmpty(rows[i + 1]["ZPPATH"].ToString()))
                {
                    Aspose.Words.Drawing.Shape shape = new Aspose.Words.Drawing.Shape(doc, Aspose.Words.Drawing.ShapeType.Image);
                    
                    //string url = System.Configuration.ConfigurationManager.AppSettings["UserPhotosSitePath"] + "\\" + rows[i + 1]["ZPPATH"].ToString();
                    string url = @"https://navisoft.oss-cn-hangzhou.aliyuncs.com/tempfile/testface2.png";

                    shape.ImageData.SetImage(url);
                    shape.Width = imgcellwidth - 2;
                    shape.Height = imgcellheight;
                    shape.HorizontalAlignment = Aspose.Words.Drawing.HorizontalAlignment.Center;
                    Aspose.Words.CompositeNode node = shape.ParentNode;
                    builder.MoveToCell(0, rowcount, 2, 0);
                    builder.InsertNode(shape);
                }
            }
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.Width = cellwidth;
            if (rows.Length > i + 1)
            {
                builder.Write(rows[i + 1]["XM"].ToString());
            }
            builder.EndRow();

            //第二行
            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = cellwidth;
            builder.Write("单位及职务:" + rows[i]["SZDW"].ToString());

            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.Width = cellwidth;
            if (rows.Length > i + 1)
            {
                builder.Write("单位及职务:" + rows[i + 1]["SZDW"].ToString());
            }
            builder.EndRow();

            //第三行
            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = cellwidth;
            builder.Write("单位电话:" + rows[i]["DWDH"].ToString());

            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.Width = cellwidth;
            if (rows.Length > i + 1)
            {
                builder.Write("单位电话:" + rows[i + 1]["DWDH"].ToString());
            }
            builder.EndRow();

            //第四行
            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = cellwidth;
            builder.Write("手机:" + rows[i]["SJHM"].ToString());

            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.Width = cellwidth;
            if (rows.Length > i + 1)
            {
                builder.Write("手机:" + rows[i + 1]["SJHM"].ToString());
            }
            builder.EndRow();

            //第五行
            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = cellwidth;
            builder.Write("邮编:" + rows[i]["DWYB"].ToString());

            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.Width = cellwidth;
            if (rows.Length > i + 1)
            {
                builder.Write("邮编:" + rows[i + 1]["DWYB"].ToString());
            }
            builder.EndRow();

            //第六行
            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = cellwidth;
            builder.Write("Email:" + rows[i]["DZYJ"].ToString());

            builder.InsertCell();

            //此单元格与上一行单元格合并
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
            builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Width = imgcellwidth;
            builder.InsertCell();
            builder.RowFormat.Height = cellheight;
            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
            builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
            builder.CellFormat.Width = cellwidth;
            if (rows.Length > i + 1)
            {
                builder.Write("Email:" + rows[i + 1]["DZYJ"].ToString());
            }
            builder.EndRow();
        }
    }
    builder.EndTable();
}

string wordFile52 = folder + @"\tempfile\testWord5-res.docx";
doc.Save(wordFile52, Aspose.Words.SaveFormat.Docx);

 

AsposeWordHelper源码下载

 

相关阅读

net中c#教程 如何创建、合并、下载、打印pdf文件?

net中c#教程 image图形操作,支持webp和svg格式

标签: Aspose.Word c#教程 net教程 数据导出
最后更新:2022年12月5日

小Q

80后中年不油腻大叔,喜欢编写代码、打羽毛球、做木制玩具。目前定居浙江杭州

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022 小Q的博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

浙ICP备2022019157号-2