C#操作word,签入书签,图表,表格

 <textarea readonly="readonly" name="code" class="c#"> 

/// <summary>
    /// 微软office
    /// </summary>
    internal class MicrosoftOfficeDocumentImpl : IDocument
    {
        /// <summary>
        /// Word应用程序变量
        /// </summary>
        private MSWord.Application _wordApp = null;

        /// <summary>
        /// Word文档变量
        /// </summary>
        private MSWord.Document _wordDoc = null;


        private object _saveChanges = null;

        private object _originalFormat = null;

        private object _routeDocument = false;

        private object _templateFilePathName = string.Empty;//模板文件名

        private object _saveAsFilePathName = string.Empty;//保存的文件路径名

        public void Initialize()
        {
            //先杀掉word进程
            KillWordProcess();
            //Word应用程序变量
            _wordApp = new MSWord.ApplicationClass();//初始化
        }

        void IDocument.InitTemplateFile(string templateFilePathName, string saveAsFilePathName)
        {
            _templateFilePathName = templateFilePathName;
            _saveAsFilePathName = saveAsFilePathName;

            object missing = System.Reflection.Missing.Value;

            _wordDoc = _wordApp.Documents.Open(ref _templateFilePathName, ref missing, ref missing,
               ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
               ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
               ref missing);//打开word模板
        }

        public void CreateWord(string filePathName)
        {
            object filePath = filePathName;
            string strContent;//文件内容
            if (File.Exists(filePathName))
            {
                File.Delete(filePathName);
            }
            //由于使用的是COM 库,因此有许多变量需要用Missing.Value 代替
            Object Nothing = Missing.Value;
            //新建一个word对象
            _wordDoc = _wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //WdSaveDocument为Word2003文档的保存格式(文档后缀.doc)\wdFormatDocumentDefault为Word2007的保存格式(文档后缀.docx)
            object format = MSWord.WdSaveFormat.wdFormatDocument;
            //将wordDoc 文档对象的内容保存为DOC 文档,并保存到path指定的路径
            _wordDoc.SaveAs(ref filePath, 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);
        }

        public void InsertBookMark(BookMark bookMark)
        {
            //KillWordProcess();
            if (_wordApp == null)
                return;
            //存在则先删除  
            if (_wordDoc.Bookmarks.Exists(bookMark.Name))  
            {
                DeleteBookMark(bookMark);  
            }
            object range = _wordApp.Selection.Range;
            _wordDoc.Bookmarks.Add(bookMark.Name, ref range);
        }

        public void DeleteBookMark(BookMark bookMark)
        {
            if (_wordDoc.Bookmarks.Exists(bookMark.Name))
            {
                var bookMarks = _wordDoc.Bookmarks;
                for (int i = 1; i <= bookMarks.Count; i++)
                {
                    object index = i;
                    var mark = bookMarks.get_Item(ref index);
                    if (mark.Name == bookMark.Name)
                    {
                        mark.Delete();
                        break;
                    }
                }
            }  
        }

        public void ReplaceBookMarkContext(IList<BookMark> bookMarks)
        {
            if (bookMarks == null)
                return;
            object missing = System.Reflection.Missing.Value;

            foreach(BookMark bookMark in bookMarks)
            {
                if (GoToBookMark(bookMark.Name))//如果书签存在
                {
                    object oStart = bookMark.Name;//word中的书签名 
                    Range range = _wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置
                    ParagraphBookMarkParam param = bookMark.Content as ParagraphBookMarkParam;
                    if (param == null)
                    {
                        throw new Exception("书签参数为空");
                    }
                    range.Text = (string)param.Context;//在书签处插入文字内容
                }
                else
                {
                    throw new Exception("书签:" + bookMark.Name + "不存在");
                }
            }
            //保存word
            object format = WdSaveFormat.wdFormatDocument;//保存格式
            //关闭wordDoc,wordApp对象              
            _saveChanges = WdSaveOptions.wdSaveChanges;
            _originalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
            _routeDocument = false;

            _wordDoc.SaveAs(ref _saveAsFilePathName, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        }

        public void InsertFigure(IList<BookMark> bookMarks)
        {
            if (bookMarks == null)
                return;
            Microsoft.Office.Interop.Graph.Chart wdchart;
            object oclasstype = "MSGraph.Chart.8";
            Microsoft.Office.Interop.Graph.DataSheet dataSheet;
            foreach (BookMark bookMark in bookMarks)
            {
                if (GoToBookMark(bookMark.Name))//如果书签存在
                {
                    FigureBookMarkParam figureBookMarkParam = bookMark.Content as FigureBookMarkParam;
                    if (figureBookMarkParam == null)
                        throw new Exception("bookMark.Context 参数为空");
                    object bookmark = bookMark.Name;
                    Range wrdrng = _wordDoc.Bookmarks.get_Item(ref bookmark).Range;
                    //清除标签区域格式
                    _wordDoc.Bookmarks[bookmark].Select();
                    _wordDoc.Application.Selection.ClearFormatting();
                    wdchart = (Microsoft.Office.Interop.Graph.Chart)wrdrng.InlineShapes.AddOLEObject(ref oclasstype).OLEFormat.Object;
                    //设置图表类型
                    wdchart.ChartType = GetFigureType(figureBookMarkParam.FType);
                    //写入图表数据
                    //清除图表原有数据
                    wdchart.Application.DataSheet.Cells.Clear();
                    dataSheet = wdchart.Application.DataSheet;
                    SetChartData(dataSheet, figureBookMarkParam);
                    //设置图表样式
                    SetChartProperty(wdchart,figureBookMarkParam);
                    wdchart.Application.Update();
                    wdchart.Application.Quit();
                    //解决标题换行问题
                    //_wordApp.ActiveDocument.Application.Selection.MoveEnd();
                    //设置图表标题
                    _wordDoc.Application.Selection.InsertCaption(WdCaptionLabelID.wdCaptionFigure, figureBookMarkParam.ChartTitle, Type.Missing, WdCaptionPosition.wdCaptionPositionBelow);
                    _wordDoc.Application.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                }
                else
                {
                    throw new Exception("书签:" + bookMark.Name + "不存在");
                }
            }
        }

        /// <summary>
        /// 设置图表属性
        /// </summary>
        /// <param name="wdchart">图表对象</param>
        /// <param name="tblx">图表类型</param>
        /// <param name="figureArg">图表参数</param>
        private void SetChartProperty(Microsoft.Office.Interop.Graph.Chart wdchart,FigureBookMarkParam figureBookMarkParam)
        {
            switch (figureBookMarkParam.FType)
            {
                case FigureType.histogram:
                case FigureType.brokenLineGraph:
                    Microsoft.Office.Interop.Graph.Axis axisX = (Microsoft.Office.Interop.Graph.Axis)wdchart.Axes(1, 1);
                    //设置X轴的属性
                    if (!string.IsNullOrEmpty(figureBookMarkParam.XChartTitle))
                    {
                        axisX.HasTitle = true;
                        // 设置X轴的标题e
                        axisX.AxisTitle.Text = figureBookMarkParam.XChartTitle;
                        axisX.AxisTitle.Font.Name = "宋体";
                        axisX.AxisTitle.Font.Size = figureBookMarkParam.XYChartTileFontSize;
                    }
                    axisX.TickLabels.Font.Name = "宋体";
                    axisX.TickLabels.Font.Size = figureBookMarkParam.XYChartTileFontSize;

                    //设置Y轴的属性
                    Microsoft.Office.Interop.Graph.Axis axisY = (Microsoft.Office.Interop.Graph.Axis)wdchart.Axes(2, 1);
                    if (!string.IsNullOrEmpty(figureBookMarkParam.YChartTitle))
                    {
                        axisY.HasTitle = true;
                        //设置Y轴的标题
                        axisY.AxisTitle.Text = figureBookMarkParam.YChartTitle;
                        axisY.AxisTitle.Font.Name = "宋体";
                        axisY.AxisTitle.Font.Size = figureBookMarkParam.XYChartTileFontSize;
                    }
                    axisY.TickLabels.Font.Name = "宋体";
                    axisY.TickLabels.Font.Size = figureBookMarkParam.XYChartTileFontSize;
                    break;
                case FigureType.pieChart:

                    break;
                default:
                    break;
            }
            //设置数据标签
            wdchart.ApplyDataLabels();

            wdchart.ChartArea.Font.Name = "宋体";
            wdchart.ChartArea.Font.Size = figureBookMarkParam.XYChartTileFontSize;
            wdchart.HasLegend = true;
            wdchart.Legend.Font.Name = "宋体";
            wdchart.Legend.Font.Size = figureBookMarkParam.XYChartTileFontSize;
            wdchart.Height = figureBookMarkParam.ChartHeight;
            wdchart.Width = figureBookMarkParam.ChartWidth;
            wdchart.Application.PlotBy = Microsoft.Office.Interop.Graph.XlRowCol.xlRows;
        }

        /// <summary>
        /// 解析图表类型
        /// </summary>
        /// <param name="tblx">图表类型</param>
        /// <returns>返回图表类型</returns>
        private Microsoft.Office.Interop.Graph.XlChartType GetFigureType(FigureType tblx)
        {
            Microsoft.Office.Interop.Graph.XlChartType figureType = new Microsoft.Office.Interop.Graph.XlChartType();
            switch (tblx)
            {
                case FigureType.histogram:
                    figureType = Microsoft.Office.Interop.Graph.XlChartType.xlColumnClustered;
                    break;
                case FigureType.brokenLineGraph:
                    figureType = Microsoft.Office.Interop.Graph.XlChartType.xlLineMarkers;
                    break;
                case FigureType.pieChart:
                    figureType = Microsoft.Office.Interop.Graph.XlChartType.xlPie;
                    break;
                default:
                    figureType = Microsoft.Office.Interop.Graph.XlChartType.xlColumnClustered;
                    break;
            }
            return figureType;
        }

        /// <summary>
        /// 设置图表数据
        /// </summary>
        /// <param name="dataSheet">数据簿</param>
        /// <param name="tblx">图表类型</param>
        /// <param name="Docarg">文书参数</param>
        /// <param name="figureArg">图表参数</param>
        private void SetChartData(Microsoft.Office.Interop.Graph.DataSheet dataSheet, FigureBookMarkParam figureBookMarkParam)
        {
            System.Data.DataTable tab = figureBookMarkParam.FigureData;
            switch (figureBookMarkParam.FType)
            {
                case FigureType.histogram:

                case FigureType.brokenLineGraph:

                case FigureType.pieChart:
                    if (tab != null && tab.Columns.Count > 0)
                    {
                        //设置列
                        for (int i = 0; i < tab.Columns.Count; i++)
                        {
                            dataSheet.Cells[1, i + 1] = tab.Columns[i].ColumnName;
                        }
                        //设置数据行
                        for (int m = 0; m < tab.Rows.Count; m++)
                        {
                            for (int j = 0; j < tab.Columns.Count; j++)
                            {
                                dataSheet.Cells[m + 2, j + 1] = tab.Rows[m][j];
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        public void InsertTable(IList<BookMark> tableParams)
        {
            if (this._wordDoc == null || tableParams == null || tableParams.Count == 0)
                return;
            for (int i = 0; i < tableParams.Count; i++)
            {
                TableBookMarkParam tableParam = tableParams[i].Content as TableBookMarkParam;
                if (GoToBookMark(tableParams[i].Name))
                {
                    if (tableParam == null)
                        throw new Exception("表格书签:" + tableParams[i].Name + "参数为空");
                    object bookmark = tableParams[i].Name;
                    Range range = _wordDoc.Bookmarks.get_Item(ref bookmark).Range;
                    //清除标签区域格式
                    _wordDoc.Bookmarks[bookmark].Select();
                    _wordDoc.Application.Selection.ClearFormatting();
                    InsertTable(tableParam, range);
                    //添加标题
                    _wordDoc.Application.Selection.InsertCaption(WdCaptionLabelID.wdCaptionFigure, tableParam.Title, Type.Missing, WdCaptionPosition.wdCaptionPositionBelow);
                    _wordDoc.Application.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                }
                else
                {
                    throw new Exception("表格书签:" + tableParams[i].Name + "不存在");
                }
            }
        }

        private void InsertTable(TableBookMarkParam tableParam, Range range)
        {
            if (this._wordDoc == null || tableParam == null || tableParam.Data == null || tableParam.Data.Rows.Count == 0)
                return;
            //创建表格
            int rows = tableParam.Data.Rows.Count + 1;
            int cols = tableParam.HeadContent.Count + 1;
            range.Tables.Add(range, rows, cols);
            Table tb = range.Tables[1];
            //创建表头
            for (int i = 0; i < tableParam.HeadContent.Count;i++ )
            {
                tb.Cell(1, i + 1).Range.Text = tableParam.HeadContent[i];
            }
            //创建数据
            for (int i = 0; i < tableParam.Data.Rows.Count;i++ )
            {
                for (int j = 0; j < tableParam.HeadContent.Count; j++)
                {
                    tb.Cell(i + 2, j + 1).Range.Text = Convert.ToString(tableParam.Data.Rows[i][j]);
                }                
            }
            //设置表格样式
            tb.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
            tb.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle; 
        }

        public void KillWordProcess()
        {
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
            foreach (System.Diagnostics.Process process in processes)
            {
                bool b = process.MainWindowTitle == "";
                if (process.MainWindowTitle == "")
                {
                    process.Kill();
                }
            }
        }


        public void Dispose()
        {
            if (_saveChanges == null)
            {
                _saveChanges = Missing.Value;
            }
            if (_originalFormat == null)
            {
                _originalFormat = Missing.Value;
            }
            //关闭wordDoc文档
            if (_wordDoc != null)
                _wordDoc.Close(ref _saveChanges, ref _originalFormat, ref _routeDocument);
            //关闭wordApp组件对象
            if (_wordApp != null)
                _wordApp.Quit(ref _saveChanges, ref _originalFormat, ref _routeDocument);
            _wordDoc = null;
            _wordApp = null;
            KillWordProcess();
        }

        /// <summary>  
        /// 光标移动到指定书签位置,书签不存在时不移动  
        /// </summary>  
        /// <param name="bookMarkName"></param>  
        /// <returns></returns>  
        public bool GoToBookMark(string bookMarkName)
        {
            object missing = System.Reflection.Missing.Value;
            //是否存在书签  
            if (_wordDoc.Bookmarks.Exists(bookMarkName))
            {
                object what = WdGoToItem.wdGoToBookmark;
                object name = bookMarkName;
                GoTo(what, missing, missing, name);
                return true;
            }
            return false;
        }

        public void GoTo(object what, object which, object count, object name)
        {
            _wordApp.Selection.GoTo(ref what, ref which, ref count, ref name);
        }
    }
</textarea>


已经将工程上传,地址:

http://download.csdn.net/download/lengyue2015/9954120

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落寞书生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值