ASP.net生成导出WORD文档

参考文章:

Asp.Net实现生成WORD或PDF文件

http://hi.baidu.com/0701u/item/a88ba8d5d2d8220d21e2503b

Asp.net动态生成Word文档并填充数据 转

http://www.cnblogs.com/ndxsdhy/archive/2011/11/15/2249555.html

ASP.NET(C#)生成Word文档

http://www.cnblogs.com/bynet/archive/2011/05/16/2047434.html


添加引用:

添加引用->COM->Microsoft Word 11.0 Object Library(电脑装的Office版本不同,引用不一样,比如我的是Office2010,所以添加的是Microsoft Word 14.0 Object Library

        //添加命名空间
        using Word=Microsoft.Office.Interop.Word;
        using Microsoft.Office.Core;
        using System.IO;


        Word._Application app = new Microsoft.Office.Interop.Word.ApplicationClass();//注意如果添加的是Office2010引用,是Word._Application,不是Word.Application,调用的是接口
        Word._Document doc=null;
        Object nothing = System.Reflection.Missing.Value;//Word中的null非C#中的null,得装换
        Object filename = Server.MapPath("word//test.docx");//服务器中要打开的文档
        doc = app.Documents.Open(ref filename, 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, ref nothing);
        foreach (Word.Bookmark bm in doc.Bookmarks)//遍历已经打开的Word文档中的标签,插入我们的数据
        {
            if (bm.Name == "range")
            {
                bm.Range.Text = "lallalallallala";
            }
            if (bm.Name == "table")
            {
                Object table = "table";//插入表格,注意已打开word文档中标签的位置,因为word中插入表格是挤占原有的位置,并非换行再插入
                Word.Range srange = bm.Range;
                Word.Table ta = doc.Tables.Add(srange, 5, 5, ref nothing, ref nothing);
                for (int i = 1; i <= 5; i++)
                {
                    for (int j = 1; j <= 5; j++)
                    {
                        ta.Cell(i, j).Range.Text = "第" + i + "行" + "第" + j + "列";
                    }
                }
            }
        }
        //关闭word,程序最好try...catch一下,因为IO流操作,如果程序出错,数据就会写到已经打开的word文档中,不会导出新的文档
        filename = Server.MapPath("word//123.doc");
        doc.SaveAs(ref filename, 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, ref nothing);
        doc.Close(ref nothing, ref nothing, ref nothing);
        app.Quit(ref nothing, ref nothing, ref nothing);
 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值