C# asp.net 操作Word的前提配置和简单的方法

操作的前提:

1.要保证机器本身要安装OFFICE.

有时安装了Office,但是不能找到Microsoft Word 11.0(或者更高的版本) Object Library。那可能是因为在安装office的时候没有选在。net可编程性支持

此时只需要重新打开office安装文件-》添加或删除功能-》下一步-》在Microsoft Word下点选。net可编程性支持

以Office 2003为例


2.用VS打开一个asp.net网站,右键单击Bin ->添加引用,在COM中选择Microsoft Word 11.0(或者更高的版本) Object Library。点击确定后会在Bin文件夹中出现

Microsoft.Office.Interop.Word.dll 

或者Interop.Word.dll 

如果没有Bin文件夹,就右键根目录,选择添加ASP.NET文件->Bin

至此前提配置就完成了


编程部分:

添加引用

using Microsoft.Office.Core;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Word;


编程打开Word文件,和Word文件夹建立连接

        object oReadOnly = true;
        object oMissing = System.Reflection.Missing.Value;
        Word._Application oWord;
        Word._Document oDoc;
        oWord = new Word.Application();
        oWord.Visible = false;//只是为了方便观察,为true时,会显示一个打开的Word
        object fileName = System.Web.HttpContext.Current.Server.MapPath("~/Resultstemplate.doc").ToString();
        oDoc = oWord.Documents.Add(ref fileName, ref oMissing, ref oMissing, ref oMissing);
关闭和Word的连接

        oDoc.Close(ref missing, ref missing, ref missing);
        oWord.Quit(ref missing, ref missing, ref missing);
对Word中的表格的数据读取,并在网页中简单显示

protected void PageFucword()
    {
        //object oMissing = System.Reflection.Missing.Value;
        //Word._Application oWord;
        //Word._Document oDoc;
        //oWord = new Word.Application();
        //oWord.Visible = true;
        //
        //oDoc = oWord.Documents.Add(ref fileName, ref oMissing,ref oMissing, ref oMissing);

        object oReadOnly = true;
        object oMissing = System.Reflection.Missing.Value;
        Word._Application oWord;
        Word._Document oDoc;
        oWord = new Word.Application();
        oWord.Visible = false;//只是为了方便观察
        object fileName = System.Web.HttpContext.Current.Server.MapPath("~/Resultstemplate.doc").ToString();
        oDoc = oWord.Documents.Add(ref fileName, ref oMissing, ref oMissing, ref oMissing);
        //MessageBox.Show(oDoc.Tables.Count.ToString());
        for (int tablePos = 1; tablePos <= oDoc.Tables.Count; tablePos++)
        {
            Word.Table nowTable = oDoc.Tables[tablePos];
            string tableMessage = string.Format("第{0}/{1}个表:\n", tablePos, oDoc.Tables.Count);
            // int i = 0;
            // foreach (Word.InlineShape shape in nowTable.Cell(28, 1).Range.InlineShapes)
            //{
            //直接读取图片
            //if (shape.Type == Word.WdInlineShapeType.wdInlineShapePicture)
            //{
            //    //获取Word中的图片
            //    byte[] img = (byte[])shape.Range.EnhMetaFileBits;
            //    Bitmap bmp = new Bitmap(new System.IO.MemoryStream(img));
            //    bmp.Save("c:\\pic" + i.ToString() + ".jpg ");
            //}
            //i++;
            //从剪切板上读取图片,还无法实现
            //if (shape.Type == Word.WdInlineShapeType.wdInlineShapePicture)
            //{
            //    shape.Select();
            //    oWord.Selection.Copy();
            //    Image image = Clipboard.GetImage();

            //    Bitmap bitmap = new Bitmap(image);
            //    bitmap.Save("c:\\pic " + i.ToString() + ".jpg ");
            //    i++;
            //}
            // } 
            Table a = new Table();
            a.Attributes["border"] = "1";
            a.Attributes["width"] = "100%";
            for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
            {
                TableRow rw = new TableRow();
                for (int columPos = 1; columPos <= nowTable.Rows[rowPos].Cells.Count; columPos++)
                {
                    TableCell tc = new TableCell();
                    if (nowTable.Columns.Count > nowTable.Rows[rowPos].Cells.Count)
                    {
                        tc.Attributes["colspan"] = nowTable.Columns.Count.ToString();
                        tc.Attributes["align"] = "center";
                    }
                    string cell = nowTable.Cell(rowPos, columPos).Range.Text;
                    if (cell.Contains(""))
                    {
                        int i = 0;
                        foreach (Word.InlineShape shape in nowTable.Cell(rowPos, columPos).Range.InlineShapes)
                        {
                            //直接读取图片                           
                            if (shape.Type == Word.WdInlineShapeType.wdInlineShapePicture)
                            {
                                System.Web.UI.WebControls.Image imgct = new System.Web.UI.WebControls.Image();
                                //获取Word中的图片
                                byte[] img = (byte[])shape.Range.EnhMetaFileBits;
                                Bitmap bmp = new Bitmap(new System.IO.MemoryStream(img));
                                string url = System.Web.HttpContext.Current.Server.MapPath("~/image/").ToString() + "pic" + i.ToString() + ".jpg ";//图片保存路径
                                bmp.Save(url);
                                imgct.ImageUrl = "~/image/" + "pic" + i.ToString() + ".jpg ";
                                imgct.Attributes["width"] = "250px";
                                tc.Controls.Add(imgct);
                                tc.Wrap = true;
                            }
                            i++;
                        }
                    }
                    else
                    {
                        cell = cell.Remove(cell.Length - 2, 2);
                        if (cell == "") cell = "空";
                        tc.Text = cell;
                        //tableMessage += cell;
                        //tableMessage = tableMessage.Remove(tableMessage.Length - 2, 2);//remove \r\a
                        //tableMessage += "\t";
                    }
                    rw.Cells.Add(tc);
                }
                //tableMessage += "\n";
                a.Rows.Add(rw);
            }
            //Label1.Text = tableMessage;
            Page.Controls.Add(a);
        }
    }

通过标签Bookmark来读取数据

Bookmark bk;

bk.Range.Cells[1];//该值得到书签所在的单元格

 public bool FruitWordToSQL()
    {
        object oReadOnly = true;
        object oMissing = System.Reflection.Missing.Value;
        Word._Application oWord;
        Word._Document oDoc;
        oWord = new Word.Application();
        //oWord.Visible = false;//只是为了方便观察
        object fileName = System.Web.HttpContext.Current.Server.MapPath("~/Resultstemplate.doc").ToString();
        oDoc = oWord.Documents.Add(ref fileName, ref oMissing, ref oMissing, ref oMissing);
        System.Collections.IEnumerator enu = oWord.ActiveDocument.Bookmarks.GetEnumerator();
        Dictionary<string, string> map = new Dictionary<string, string>();//数据项(项名,项值)
        while (enu.MoveNext())
        {
            Word.Bookmark bk = (Word.Bookmark)enu.Current;
            string text = bk.Name.ToString();
            string value=bk.Range.Cells[1].Range.Text;//书签所在单元格的内容
            value = value.Remove(value.Length - 2);//去除单元格后的标记(/r/n)
            map.Add(text,value);
        }
        //对word的操作结束,关闭对word的控制
        oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
        oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        //检验数据的格式及正确性
        KeyValuePair<bool,string> check=CheckData(map);
        if (check.Key == false)
        {
            //check.Value中所含的值为数据检验不符合标准的第一个数据的值
            return false;
        }
        //map中的数据插入到数据库的Fruit表中
        bool Inserted=InsertData(map);
        if (Inserted == false)//插入失败
        { 
            //插入失败后的操作
            return false;
        }
        return true;
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值