2010-01-19 10:32:41|  分类: Office操作
|  标签:
|字号 订阅





using System


using System.Collections.Generic;


using System.Text;


using Microsoft.Office.Interop.Word;


using System.IO;


using System.Web;


using System.Data;


using System.Reflection;


using Microsoft.Win32;


using System.Text.RegularExpressions;


using System.Net;


namespace OfficeOperate


{


    public class WordOperate


    {


        #region 动态生成Word文档并填充数据


        /**//// <summary>


        /// 动态生成Word文档并填充数据


        /// </summary>


        ///
<returns>返回自定义信息</returns>


        public static string CreateWordFile()


        {


            string message = "";


            try


            {


                Object oMissing =
System.Reflection.Missing.Value;


                string dir =
System.Web.HttpContext.Current.Server.MapPath( "" );//首先在类库添加using
System.web的引用


                if( !Directory.Exists( dir + "file://file/" ) )


                {


                    Directory.CreateDirectory( dir +
"file://file/" ); //创建文件所在目录


                }


                string name =
DateTime.Now.ToLongDateString() + ".doc";


                object filename = dir + "file://file//" + name; //文件保存路径


                //创建Word文档


               
Microsoft.Office.Interop.Word.Application WordApp = new
Microsoft.Office.Interop.Word.ApplicationClass();


               
Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add( ref
oMissing, ref oMissing, ref oMissing, ref oMissing );


                /**/////添加页眉方法一:


                //WordApp.ActiveWindow.View.Type =
WdViewType.wdOutlineView;


                //WordApp.ActiveWindow.View.SeekView
= WdSeekView.wdSeekPrimaryHeader;


               
//WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "无锡全真通科技有限公司"
);//页眉内容


                //添加页眉方法二:


                if(
WordApp.ActiveWindow.ActivePane.View.Type ==
Microsoft.Office.Interop.Word.WdViewType.wdNormalView ||
WordApp.ActiveWindow.ActivePane.View.Type ==
Microsoft.Office.Interop.Word.WdViewType.wdOutlineView )


                {


                   
WordApp.ActiveWindow.ActivePane.View.Type =
Microsoft.Office.Interop.Word.WdViewType.wdPrintView;


                }


                WordApp.ActiveWindow.View.SeekView =
Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;


                string sHeader = "页眉内容";


               
WordApp.Selection.HeaderFooter.LinkToPrevious = false;


               
WordApp.Selection.HeaderFooter.Range.Text = sHeader;


                WordApp.ActiveWindow.View.SeekView =
Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;


               
//WordApp.Selection.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐


               
WordApp.Selection.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;//设置左对齐  


                WordApp.ActiveWindow.View.SeekView =
WdSeekView.wdSeekMainDocument;//跳出页眉设置


               
WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距


                //移动焦点并换行


                object count = 14;


                object WdLine =
Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;


                WordApp.Selection.MoveDown( ref
WdLine, ref count, ref oMissing );//移动焦点


               
WordApp.Selection.TypeParagraph();//插入段落


                //文档中创建表格


                Microsoft.Office.Interop.Word.Table
newTable = WordDoc.Tables.Add( WordApp.Selection.Range, 12, 3, ref oMissing, ref
oMissing );


                //设置表格样式


                newTable.Borders.OutsideLineStyle =
Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;


                newTable.Borders.InsideLineStyle =
Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;


                newTable.Columns[1].Width =
100f;


                newTable.Columns[2].Width =
220f;


                newTable.Columns[3].Width =
105f;


                //填充表格内容


                newTable.Cell( 1, 1 ).Range.Text =
"产品详细信息表";


                newTable.Cell( 1, 1 ).Range.Bold =
2;//设置单元格中字体为粗体


                //合并单元格


                newTable.Cell( 1, 1 ).Merge(
newTable.Cell( 1, 3 ) );


               
WordApp.Selection.Cells.VerticalAlignment =
Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中


               
WordApp.Selection.ParagraphFormat.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中


                //填充表格内容


                newTable.Cell( 2, 1 ).Range.Text =
"产品基本信息";


                newTable.Cell( 2, 1
).Range.Font.Color =
Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色


                //合并单元格


                newTable.Cell( 2, 1 ).Merge(
newTable.Cell( 2, 3 ) );


               
WordApp.Selection.Cells.VerticalAlignment =
Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;


                //填充表格内容


                newTable.Cell( 3, 1 ).Range.Text =
"品牌名称:";


                newTable.Cell( 3, 2 ).Range.Text =
"BrandName";


                //纵向合并单元格


                newTable.Cell( 3, 3
).Select();//选中一行


                object moveUnit =
Microsoft.Office.Interop.Word.WdUnits.wdLine;


                object moveCount = 5;


                object moveExtend =
Microsoft.Office.Interop.Word.WdMovementType.wdExtend;


                WordApp.Selection.MoveDown( ref
moveUnit, ref moveCount, ref moveExtend );


                WordApp.Selection.Cells.Merge();


                //插入图片


                if( File.Exists(
System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" ) ) )


                {


                    string FileName =
System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg"
);//图片所在路径


                    object LinkToFile = false;


                    object SaveWithDocument =
true;


                    object Anchor =
WordDoc.Application.Selection.Range;


                   
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture( FileName, ref
LinkToFile, ref SaveWithDocument, ref Anchor );


                   
WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度


                   
WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度


                }


                //将图片设置为四周环绕型


                Microsoft.Office.Interop.Word.Shape
s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();


                s.WrapFormat.Type =
Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;


                newTable.Cell( 12, 1 ).Range.Text =
"产品特殊属性";


                newTable.Cell( 12, 1 ).Merge(
newTable.Cell( 12, 3 ) );


                //在表格中增加行


                WordDoc.Content.Tables[1].Rows.Add(
ref oMissing );


                WordDoc.Paragraphs.Last.Range.Text =
"文档创建时间:" + DateTime.Now.ToString();//“落款”


                WordDoc.Paragraphs.Last.Alignment =
Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;


                //文件保存


                WordDoc.SaveAs( ref filename, ref
oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref
oMissing, ref oMissing, ref oMissing, ref oMissing );


                WordDoc.Close( ref oMissing, ref
oMissing, ref oMissing );


                WordApp.Quit( ref oMissing, ref
oMissing, ref oMissing );


                message = name + "文档生成成功";


            }


            catch


            {


                message = "文件导出异常!";


            }


            return message;


        }


        #endregion      


        #region 创建并打开一个空的word文档进行编辑


        /**//// <summary>


        /// 创建并打开一个空的word文档进行编辑


        /// </summary>


        public static void
OpenNewWordFileToEdit()


        {


            object oMissing =
System.Reflection.Missing.Value;


           
Microsoft.Office.Interop.Word.Application WordApp;


            Microsoft.Office.Interop.Word.Document
WordDoc;


            WordApp = new
Microsoft.Office.Interop.Word.ApplicationClass();


            WordApp.Visible = true;


            WordDoc = WordApp.Documents.Add( ref
oMissing, ref oMissing, ref oMissing, ref oMissing );


        }


        #endregion


        #region 创建word文档


        /**//// <summary>


        /// 创建word文档


        /// </summary>


        /// <returns></returns>


        public static string createWord()


        {


           
Microsoft.Office.Interop.Word.Application WordApp = new
Microsoft.Office.Interop.Word.ApplicationClass();


            Document WordDoc;


            string strContent = "";


            object strFileName =
System.Web.HttpContext.Current.Server.MapPath( "test.doc " );


            if( System.IO.File.Exists(
(string)strFileName ) )


                System.IO.File.Delete(
(string)strFileName );


            Object oMissing =
System.Reflection.Missing.Value;


            WordDoc = WordApp.Documents.Add( ref
oMissing, ref oMissing, ref oMissing, ref oMissing );


            #region   将数据库中读取得数据写入到word文件中


            strContent = "你好\n\n\r ";


            WordDoc.Paragraphs.Last.Range.Text =
strContent;


            strContent = "这是测试程序 ";


            WordDoc.Paragraphs.Last.Range.Text =
strContent;


            #endregion


            //将WordDoc文档对象的内容保存为DOC文档  


WordDoc.SaveAs( ref strFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing );


            //关闭WordDoc文档对象  


            WordDoc.Close( ref oMissing, ref
oMissing, ref oMissing );


            //关闭WordApp组件对象  


            WordApp.Quit( ref oMissing, ref
oMissing, ref oMissing );


            string message = strFileName + "\r\n " +
"创建成功 ";


            return message;


        }


        #endregion


        #region 把Word文档装化为Html文件


        /**//// <summary>


        /// 把Word文档装化为Html文件


        /// </summary>


        /// <param
name="strFileName">要转换的Word文档</param>


        public static void WordToHtml( string
strFileName )


        {


            string saveFileName = strFileName +
DateTime.Now.ToString( "yyyy-MM-dd-HH-mm-ss" ) + ".html";


            WordToHtml( strFileName, saveFileName
);


        }


        /**//// <summary>


        /// 把Word文档装化为Html文件


        /// </summary>


        /// <param
name="strFileName">要转换的Word文档</param>


        /// <param
name="strSaveFileName">要生成的具体的Html页面</param>


        public static void WordToHtml( string
strFileName, string strSaveFileName )


        {


           
Microsoft.Office.Interop.Word.ApplicationClass WordApp;


            Microsoft.Office.Interop.Word.Document
WordDoc;


            Object oMissing =
System.Reflection.Missing.Value;


            WordApp = new
Microsoft.Office.Interop.Word.ApplicationClass();


            object fileName = strFileName;


           


            WordDoc = WordApp.Documents.Open( ref
fileName,


               ref oMissing, ref oMissing, ref
oMissing, ref oMissing, ref oMissing,


               ref oMissing, ref oMissing, ref
oMissing, ref oMissing, ref oMissing,


               ref oMissing, ref oMissing, ref
oMissing, ref oMissing, ref oMissing );


            Type wordType = WordApp.GetType();


            // 打开文件


            Type docsType =
WordApp.Documents.GetType();


            // 转换格式,另存为


            Type docType = WordDoc.GetType();


            object saveFileName =
strSaveFileName;


            docType.InvokeMember( "SaveAs",
System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] {
saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML } );


            #region 其它格式:


            /**//**/


            /**////wdFormatHTML


            ///wdFormatDocument


            ///wdFormatDOSText


            ///wdFormatDOSTextLineBreaks


            ///wdFormatEncodedText


            ///wdFormatRTF


            ///wdFormatTemplate


            ///wdFormatText


            ///wdFormatTextLineBreaks


            ///wdFormatUnicodeText


           
//-----------------------------------------------------------------------------------


            //            docType.InvokeMember(
"SaveAs", System.Reflection.BindingFlags.InvokeMethod,


            //                null, WordDoc, new
object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );


            // 退出 Word


            //wordType.InvokeMember( "Quit",
System.Reflection.BindingFlags.InvokeMethod,


            //    null, WordApp, null );


            #endregion


            WordDoc.Close( ref oMissing, ref
oMissing, ref oMissing );


            WordApp.Quit( ref oMissing, ref
oMissing, ref oMissing );


        }


        #endregion


        #region 导入模板


        /**//// <summary>


        /// 导入模板


        /// </summary>


        /// <param
name="filePath">模板文档路径</param>


        public static void ImportTemplate(
string filePath )


        {


            object oMissing =
System.Reflection.Missing.Value;


           
Microsoft.Office.Interop.Word.Application WordApp;


            Microsoft.Office.Interop.Word.Document
WordDoc;


            WordApp = new
Microsoft.Office.Interop.Word.ApplicationClass();


            WordApp.Visible = true;


            object fileName = filePath;


            WordDoc = WordApp.Documents.Add( ref
fileName, ref oMissing, ref oMissing, ref oMissing );


        }


        #endregion


        #region word中添加新表


        /**//// <summary>


        /// word中添加新表


        /// </summary>


        public static void AddTable()


        {


            object oMissing =
System.Reflection.Missing.Value;


           
Microsoft.Office.Interop.Word.Application WordApp;


            Microsoft.Office.Interop.Word.Document
WordDoc;


            WordApp = new
Microsoft.Office.Interop.Word.ApplicationClass();


            WordApp.Visible = true;


            WordDoc = WordApp.Documents.Add( ref
oMissing, ref oMissing, ref oMissing, ref oMissing );


            object start = 0;


            object end = 0;


            Microsoft.Office.Interop.Word.Range
tableLocation = WordDoc.Range( ref start, ref end );


            WordDoc.Tables.Add( tableLocation, 3, 4,
ref oMissing, ref oMissing );//3行4列的表


        }


        #endregion