C#整合layui实现导出带多张图片的word文档

    最近研究了一下如何实现利用C# webapi方式导出word文档,且文档中包含多张图片,现在给出实现过程。

准备阶段:

 开发工具vs2017,在项目引用那里右键点击管理NuGet程序包,查询找到word依赖,如下图所示:

下载版本如下图所示,考虑到有的电脑可能装的word版本比较低,因此不需要下载最新稳定包

然后就是安装此依赖,下面开始代码部分

前端:

前端开发使用了web storm2018,开发思路,提供一份表单,文本域部分给用户输入文字部分,上传按钮提供未来需要插入到word中的图片,上传采用多文件上传方式

html部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>导出主题</title>
    <link rel="stylesheet" type="text/css" href="layui/css/layui.css" />
    <script type="text/javascript" src="layui/layui.js"></script>
    <script type="text/javascript" src="scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="scripts/bootstrap.js"></script>
</head>
<body style="padding: 20px" width="90%">
<div class="layui-form" action="" lay-filter="breakForm">
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">标题</label>
        <div class="layui-input-block">
            <input type="text" id="title" name="title" value="XXX案例库" class="layui-input" autocomplete="off" />
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">作者及机构</label>
        <div class="layui-input-block">
            <input type="text" id="author" name="author" value="严康    楚航公司" class="layui-input" autocomplete="off" />
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">中文摘要</label>
        <div class="layui-input-block">
            <textarea id="abstract1" name="abstract1" class="layui-textarea"  autocomplete="off" >武汉是国家历史文化名城,楚文化的重要发祥地,境内盘龙城遗址有3500年历史。春秋战国以来,武汉一直是中国南方的军事和商业重镇,明清时期成为“楚中第一繁盛处”、天下四聚之一。清末汉口开埠和洋务运动开启武汉现代化进程,使其成为近代中国重要的经济中心,被誉为“东方芝加哥”。武汉是辛亥革命首义之地,近代史上数度成为全国政治、军事、文化中心</textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">中文关键字</label>
        <div class="layui-input-block">
            <input type="text" id="keyword1" name="keyword1" class="layui-input" value="武汉 重镇" autocomplete="off" />
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">英文摘要</label>
        <div class="layui-input-block">
            <textarea id="abstract2" name="abstract2" class="layui-textarea" autocomplete="off" >Wuhan is a national historical and cultural city and an important birthplace of Chu culture. The site of Panlong City in its territory has a history of 3,500 years. Since the Spring and Autumn Period and the Warring States Period, Wuhan has always been a military and commercial center in southern China. The opening of a port in Hankou and the Westernization Movement in the late Qing Dynasty started the modernization process of Wuhan, making it an important economic center of modern China, known as the "Chicago of the East". Wuhan is the place where the Revolution of 1911 was the first place, and it has become the political, military and cultural center of the country several times in modern history.</textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">英文关键字</label>
        <div class="layui-input-block">
            <input type="text" id="keyword2" name="keyword2" class="layui-input" value="wuhan,Important town" autocomplete="off" />
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">正文引言</label>
        <div class="layui-input-block">
            <textarea id="foreword" name="foreword" class="layui-textarea" autocomplete="off" >武汉,简称“汉”,别称江城,是湖北省省会,中部六省唯一的副省级市,特大城市,中国中部地区的中心城市,全国重要的工业基地、科教基地和综合交通枢纽,联勤保障部队机关驻地。截至2020年末,全市下辖13个区,总面积8569.15平方千米,常住人口1232.65万人(第七次全国人口普查),地区生产总值1.56万亿元。</textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">背景介绍</label>
        <div class="layui-input-block">
            <textarea id="backgroud" name="backgroud" class="layui-textarea" autocomplete="off" >武汉地处江汉平原东部、长江中游,长江及其最大支流汉江在城中交汇,形成武汉三镇(武昌、汉口、汉阳)隔江鼎立的格局,市内江河纵横、湖港交织,水域面积占全市总面积四分之一。作为中国经济地理中心,武汉有“九省通衢”之称,是中国内陆最大的水陆空交通枢纽和长江中游航运中心,其高铁网辐射大半个中国,是华中地区唯一可直航全球五大洲的城市。</textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">主题内容</label>
        <div class="layui-input-block">
            <textarea id="content" name="content" class="layui-textarea" autocomplete="off" >武汉地区考古发现的历史可以上溯到距今8000年—6000年前的新石器时代早、中期,其考古发现有东湖放鹰台遗址的含有稻壳的红烧土、石斧、石锛以及鱼叉。市郊黄陂境内的张西湾古城遗址为4300年前古人类生活的重要遗存。盘龙城遗址是距今约3500年前的商朝方国宫城。春秋战国时期,武汉属楚国管辖。
武汉地方建制始于西汉,为江夏郡沙羡县地。东汉末年,在今汉阳先后兴建却月城和鲁山城,在今武昌蛇山兴建夏口城。时荆州牧刘表派黄祖为江夏太守,将郡治设在位于今汉阳龟山的“却月城”中,“却月城”遂成为武汉市区内已知的最早城堡。吴黄武二年(223年),东吴孙权在武昌蛇山修筑夏口城,同时在城内的黄鹄矶上修筑瞭望塔,取名黄鹤楼。南朝时,夏口扩建为郢州,成为郢州的治所。
</textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" style="text-align: center">总结</label>
        <div class="layui-input-block">
            <textarea  id="tailer" name="tailer" class="layui-textarea" autocomplete="off" >民国十八年(1929年)6月21日,湖北省政府组建武昌市政委员会。民国二十年(1931年)4月,武昌市政委员会改为武昌市政筹备处。1945年抗日战争胜利,武汉光复。民国三十五年(1946年)10月1日,武昌市政府成立,市辖区域面积66平方千米,人口176379人,市区范围东北至任家路,西南至白沙洲,东南至洪山口,西北至长江中线,辖中正、大朝街、宾阳、粮道街、胡林翼、积玉桥、金白洲、徐家棚8个镇公所。12月1日,将镇公所改区。民国三十五年(1946年),汉阳城区划归武昌市管辖。</textarea>
        </div>
    </div>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
        <legend>上传附件图片</legend>
    </fieldset>
    <!--<div class="layui-upload">-->
    <div class="layui-form-item">
        <button type="button" class="layui-btn" id="test2" name="test2">多图片上传</button>
        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
            预览图:
            <div class="layui-upload-list" id="demo2" name="demo2"></div>
        </blockquote>
    </div>
    <div class="layui-form-item">
        <div class="layui-col-lg-offset10 layui-col-md-offset10 layui-col-sm-offset10 layui-col-xs-offset10">
            <!--<button id="btn123" class="layui-btn"  lay-submit lay-filter="*" >导出</button>-->
            <input type="button" id="btn123" value="导出" class="layui-btn layui-btn-danger"/>
        </div>
    </div>
</div>

js部分

<script>
    layui.use(['form', 'laydate', 'layer','upload'], function () {
       // let form = layui.form;
        let layer = layui.layer;
        let upload = layui.upload;
        let imgArr=[];

        //多图片上传
        upload.render({
            elem: '#test2'
            ,url: ApiUrl+'Query/mutiUpload2/' //此处配置你自己的上传接口即可
            ,multiple: true
            ,before: function(obj){
                //预读本地文件示例,不支持ie8
                obj.preview(function(index, file, result){
                    /*console.log(index); //得到文件索引
                    console.log(file); //得到文件对象
                    console.log(result); //得到文件base64编码,比如图片*/
                    $('#demo2').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img" style="width: 100px;height: 100px;">');
                });
            }
            ,done: function(res){
                //上传完毕
                console.log('上传完毕后res',res);
                imgArr.push(res.data);//将之前保存的文件路径保存下来
            }
        });


        $("#btn123").click(function () {
            //console.log('btn123被点击....');
            let btn=$("#btn123");
            btn.addClass("layui-btn-disabled");
            btn.attr("disabled", "true");
            //获取表单中的值
            let title=$("#title").val();
            let author=$("#author").val();
            let abstract1=$("#abstract1").val();
            let abstract2=$("#abstract2").val();
            let keyword1=$("#keyword1").val();
            let keyword2=$("#keyword2").val();
            let foreword=$("#foreword").val();
            let backgroud=$("#backgroud").val();
            let content=$("#content").val();
            let tailer=$("#tailer").val();
            let filename='';
            //console.log('imgArr:',imgArr);
            $.ajax({
                type: "post",
                url:ApiUrl+"Query/exportWord",
                async: true,//这里必须使用true,否则按钮失效样式不可用
                data:{
                    'title':title,
                    'author':author,
                    'abstract1':abstract1,
                    'abstract2':abstract2,
                    'keyword1':keyword1,
                    'keyword2':keyword2,
                    'foreword':foreword,
                    'backgroud':backgroud,
                    'content':content,
                    'tailer':tailer,
                    'imgArr':imgArr
                },
                //contentType: "application/x-www-form-urlencoded;charset=UTF-8",//不写contentType,默认就是这个
                dataType: "json",
                success: function (s) {
                    console.log("s", s);
                    if(s.code==="200") {
                        filename =s.data;
                        //2.下载这个刚刚生成好的word文件
                        if(filename!==''){
                            let url = ApiUrl +"Query/download2?filePath=E:/uploadM/"+filename+"&fileName="+'案例教学素材库.doc';
                            //执行下载
                            download(url);
                        }else{
                            layer.msg("导出文档失败");
                        }
                        btn.removeClass("layui-btn-disabled");
                        btn.removeAttr("disabled");
                    }
                },
                error: function (error) {
                    layer.msg(error);
                }
            });
            return false;
        });
//下载通用代码
function download(getur) {
    let str = document.createElement("a");//创建a标签
    str.href = getur;
    document.body.appendChild(str);
    str.click();
    str.style.display = "none";//隐藏标签
}

后端:

使用C# webapi方式

引用部分:

using System.Data;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Web;
using DAL;
using System.Net.Http.Headers;
using System.Collections.Specialized;
using MSWord = Microsoft.Office.Interop.Word;
using System.Reflection;
using Microsoft.Office.Interop.Word;

多文件上传部分代码


        [HttpPost]//导出word的多图片上传
        public ResponesData mutiUpload2()
        {
            //获取从前端传过来的数据
            //string url = HttpContext.Current.Server.MapPath("~/Upload");
            HttpFileCollection filelist = HttpContext.Current.Request.Files;
            ResponesData res = new ResponesData();
            if (filelist != null && filelist.Count > 0)//实际前端每次只传一个文件,count最大是1
            {
                for (int i = 0; i < filelist.Count; i++)
                {
                    HttpPostedFile file = filelist[i];
                    String Tpath = DateTime.Now.ToString("yyyy-MM-dd");
                    string filename = file.FileName;
                    
                    string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");//精确到毫秒,同名文件也不会冲突
                    string FilePath = "E:/uploadM/";//新建到当前日期的下一级目录
                    DirectoryInfo di = new DirectoryInfo(FilePath);//根据日期创建文件夹
                    //文件夹不存在时,创建
                    if (!di.Exists)
                    {
                        di.Create();
                    }
                    try
                    {
                        string fileUrl = FilePath + FileName+ filename; ;//文件路径,文件名,
                        file.SaveAs(fileUrl);//保存文件到项目部署的磁盘位置
                        res.code = "200";
                        res.data = fileUrl;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        log.Error("Query/mutiUpload2方法报错", ex);
                        res.code = "500";
                    }
                }
                return res;
            }
            else
            {
                res.code = "404";
                return res;
            }
        }

导出word和图片的核心代码:

 public ResponesData exportWord(JObject jsonObj)
        {
            ResponesData res = new ResponesData();
            string title,author,abstract1,keyword1, abstract2, keyword2,foreword, backgroud, content, tailer;
            var jsonParams = commonMethod(jsonObj);
            title = jsonParams.title;
            author= jsonParams.author;
            abstract1= jsonParams.abstract1;
            abstract2 = jsonParams.abstract2;
            keyword1= jsonParams.keyword1;
            keyword2 = jsonParams.keyword2;
            foreword = jsonParams.foreword;
            backgroud = jsonParams.backgroud;
            content = jsonParams.content;
            tailer = jsonParams.tailer;
            List<string> picList=new List<string>();
            if (jsonParams.imgArr != null)
            {
                dynamic dy = JsonConvert.DeserializeObject(jsonParams.imgArr.ToString());
                picList = dy.ToObject<List<string>>();
            }
            //导出word核心代码
            string param= createWord(title, author, abstract1, keyword1, abstract2, keyword2, foreword, backgroud, content, tailer, picList);
            if (param != "500")
            {
                res.data = param;
                res.code = "200";
            }
            else
            {
                res.code = "500";
            }
            return res;
        }

//生成word核心代码
        private string createWord(string title, string author, string abstract1,string keyword1, string abstract2,string keyword2, string foreword, string backgroud, string content, string tailer,List<string> picList )
        {
            try
            {
                //由于使用的是COM库,因此有许多变量需要用Missing.Value代替
                object Nothing = Missing.Value;
                string name = "" + DateTime.Now.Ticks + ".doc";//此处已经指定导出word2003格式
                object path = @"E:\uploadM\" + name;//映射固定磁盘位置
                //object path = HttpContext.Current.Server.MapPath("~/WordTempPath/" + name);//开发环境下,服务端映射WordTempPath的位置
                //object path2 = Environment.CurrentDirectory + "\\WordTempPath\\"+name;//部署在服务端位置的写法
                //创建Word文档
                Application WordApp = new ApplicationClass();//Word应用程序变量,并初始化
                WordApp.Visible = false;//设置为true,则word文档直接弹出并打开给用户看到,false为不打开
                Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);//Word文档变量

                //页面设置
                WordDoc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;//设置纸张样式为A4纸
                WordDoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait;//排列方式为垂直方向
                WordDoc.PageSetup.TopMargin = 104.92f;
                WordDoc.PageSetup.BottomMargin = 99.25f;
                WordDoc.PageSetup.LeftMargin = 79.40f;
                WordDoc.PageSetup.RightMargin = 73.73f;

                //设置页眉,添加页眉文字
                if (WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdOutlineView)
                {
                    WordApp.ActiveWindow.ActivePane.View.Type = WdViewType.wdPrintView;
                }
                WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
                WordApp.Selection.HeaderFooter.LinkToPrevious = false;
                WordApp.Selection.HeaderFooter.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                WordApp.Selection.HeaderFooter.Range.Text = "案例素材库介绍";
                WordApp.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;//退出页眉设置


                //行间距与缩进、文本字体(Name)、字号(Size)、加粗(Bold)、斜体(Italic)、颜色、下划线、下划线颜色设置
                WordApp.Selection.ParagraphFormat.LineSpacing = 16f;//设置文档的行间距
                WordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行缩进的长度

                //以下是正文开始部分
                //定义需要写入的内容变量
                string strContent;
                //1.标题
                strContent = title;
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
                WordDoc.Paragraphs.Last.Range.Font.Size = 16;//3号字
                WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//本行居中
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容
                //2.作者,单位
                strContent = author;
                commonCode(WordDoc,WordApp);
                WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 14;//4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;//本行居右
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容
                //WordDoc.Content.InsertAfter("就写这么多,算了吧!2016.09.27");
                //3.中文摘要题目
                strContent ="摘要";
                commonCode(WordDoc, WordApp);
                WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 14;//4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//不加粗
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//本行居中
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容
                //3.中文内容部分
                strContent = abstract1;
                commonCode(WordDoc, WordApp);
                WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 12;//小4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 0;//不加粗
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //4.中文关键字
                strContent ="关键字:"+keyword1;
                commonCode(WordDoc, WordApp);
                WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 12;//小4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //5英文摘要题目
                strContent = "Abstract";
                commonCode(WordDoc, WordApp);
                WordDoc.Paragraphs.Last.Range.Font.Name = "Times New Roman";
                WordDoc.Paragraphs.Last.Range.Font.Size = 14;//4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//本行居中
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //5英文摘要内容
                strContent = abstract2;
                commonCode(WordDoc, WordApp);
                WordDoc.Paragraphs.Last.Range.Font.Name = "Times New Roman";
                WordDoc.Paragraphs.Last.Range.Font.Size = 12;//小4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 0;//不加粗
                WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //6英文摘要关键字
                strContent = "KeyWords:" + keyword2;
                commonCode(WordDoc, WordApp);
                WordDoc.Paragraphs.Last.Range.Font.Name = "Times New Roman";
                WordDoc.Paragraphs.Last.Range.Font.Size = 12;//小4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
             //   WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //7引言标题
                strContent = "一 引言";
                commonCode(WordDoc, WordApp);
                WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 14;//4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
              //  WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //7引言正文
                strContent =foreword;
                commonCode(WordDoc, WordApp);
                //WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 12;//小4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 0;//不加粗
                //WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //8二 背景介绍标题
                strContent = "二 背景介绍";
                commonCode(WordDoc, WordApp);
                //WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 14;//4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
                //WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //8 背景介绍正文
                strContent = backgroud;
                commonCode(WordDoc, WordApp);
                //WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 12;//小4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 0;//不加粗
                //WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //9三 主题内容标题
                strContent = "三 主题内容";
                commonCode(WordDoc, WordApp);
                //WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 14;//4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
                //WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //9 主题内容正文
                strContent = content;
                commonCode(WordDoc, WordApp);
                //WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 12;//小4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 0;//不加粗
                //WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //10四 结尾标题
                strContent = "四 结尾";
                commonCode(WordDoc, WordApp);
                //WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 14;//4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗
                //WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //10 结尾内容正文
                strContent = tailer;
                commonCode(WordDoc, WordApp);
                //WordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
                WordDoc.Paragraphs.Last.Range.Font.Size = 12;//小4号字
                WordDoc.Paragraphs.Last.Range.Font.Bold = 0;//不加粗
                //WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//本行居左
                WordDoc.Paragraphs.Last.Range.Text = strContent;//赋值加入的内容

                //11插入图片实现

                #region  测试多次插入图片
                if (picList.Count > 0)
                {
                    string filename;
                    object range, linkToFile, saveWithDocument;
                    for (int picIndex = 0; picIndex < picList.Count; picIndex++)
                    {
                        commonCode(WordDoc, WordApp);
                        //图片文件的路径
                        filename = picList[picIndex];
                        //要向Word文档中插入图片的位置,//以对象的形式返回集合中的最后一项 Paragraphs Paragraph 。
                        range = WordDoc.Application.Selection.Range;
                        //定义该插入的图片是否为外部链接
                        linkToFile = false;
                        //定义要插入的图片是否随Word文档一起保存
                        saveWithDocument = true;
                        WordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range);
                        WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//居中显示图片
                        WordDoc.InlineShapes[picIndex+1].ScaleWidth = 20;//缩小到20% 
                        WordDoc.InlineShapes[picIndex+1].ScaleHeight = 20;
                        commonCode(WordDoc, WordApp);
                        WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                        WordApp.Selection.Font.Size = 10;//字体大小
                        WordApp.Selection.TypeText("图" + (picIndex + 1) + "案例图片\n");
                        //将上传的图片删除,因为图片已经导入到word文档里面了
                        File.Delete(filename);
                    }
                }
                #endregion

                //以下为保存word公共部分代码***********************************
                //WdSaveFormat为Word 2003文档的保存格式
                object format = WdSaveFormat.wdFormatDocument;// office 2007就是wdFormatDocumentDefault
                //将wordDoc文档对象的内容保存为DOCX文档
                WordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                //关闭wordDoc文档对象
                WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                //关闭wordApp组件对象
                WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

                //启动定时器,10秒后删除刚才创建的文件
                MyThread.GetTimerStart(path.ToString());//这个自己研究,不再贴代码了,很简单
                return "200";
            }
            catch (Exception exp)
            {
                log.Error("导出失败!" + exp.Message.ToString());
                return "500";
            }
        }

        //写文字通用方法
        private void commonCode(Document WordDoc, Application WordApp)
        {

            object unite = WdUnits.wdStory;
            object Nothing = Missing.Value;
            //注意:以下语句不能颠倒顺序,否则会导致段落字体样式失效
            WordDoc.Content.InsertAfter("\n");//在内容后新开一行
            WordApp.Selection.EndKey(ref unite, ref Nothing);//将光标移到文本末尾
        }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值