C#操作word之插入图片

假如我们导出一份简历到word文档,那势必可能要同时导出我们包含的简历,下面就来试一下如何和通过C#代码,将图片插入到word文档中。

为了简便起见,就简单一点。类似下面这样的

姓名 张三
照片  
 protected void InsertPtctureToExcel()
        {
            Word.Application app = null;
            Word.Document doc = null;
            try
            {
                object oMissing = System.Reflection.Missing.Value;
                //图片地址
                string fileName =Server.MapPath("photo.jpg");
                object linkToFile = false;
                object saveWithDocument = true;

                app = new Word.Application();
                doc = app.Documents.Add();
                Word.Table table = doc.Tables.Add(app.Selection.Range, 2, 2);
                table.Columns[1].Width = 100f;
                table.Columns[2].Width = 125f;
                table.Cell(1, 1).Range.Text = "姓名";
                table.Cell(1, 2).Range.Text = "张三";
                table.Cell(2,1).Range.Text = "照片";
                table.Cell(2, 2).Select();

                object range = app.Selection.Range;
                Word.InlineShape shape =  app.ActiveDocument.InlineShapes.AddPicture(fileName, ref linkToFile, ref saveWithDocument, ref range);
                shape.Width = 100f;//图片宽度
                shape.Height = 120f;//图片高度
                shape.ConvertToShape().WrapFormat.Type = Word.WdWrapType.wdWrapSquare;//四周环绕的方式
                string newFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc";
                string physicNewFile = Server.MapPath(newFile);
                doc.SaveAs(physicNewFile);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭文档
                }
                if (app != null)
                {
                    app.Quit();//退出应用程序
                }
            }
        }

 

posted @ 2013-06-16 17:17  自由小菜园  阅读(19999)  评论(1编辑  收藏  举报