C#导出成WORD文档

 /// <summary>
        /// 导出WORD文档
        /// </summary>
        /// <param name="SaveWordName">用于接受SaveFileDialog传过来的保存文件的名称</param>
        /// <param name="MyDGV">要导出的表</param>
        private void ExportWord(string SaveWordName, DataGridView MyDGV)
        {
            try
            {
                //新建文档
                Word.Application newapp = new Word.Application();
                Word.Document newdoc;
                object nothing = System.Reflection.Missing.Value;   //用于作为函数的默认参数
                newdoc = newapp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);  //生成一个word文档
                newapp.Visible = true;  //是否显示word程序界面

                //页面设置
                newdoc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4;
                newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait;
                newdoc.PageSetup.TopMargin = 57.0f;
                newdoc.PageSetup.BottomMargin = 57.0f;
                newdoc.PageSetup.LeftMargin = 57.0f;
                newdoc.PageSetup.RightMargin = 57.0f;
                newdoc.PageSetup.HeaderDistance = 30.0f;    //页眉位置

                //设置页眉
                //newapp.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView;  //视图样式
                //newapp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;    //进入页眉设置,其中页眉边距在页面设置中已完成
                //newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

                //插入页眉图片
                //string headerfile = "x:\\xxxx.jpg";
                ////this.outpicture(headerfile, Properties.Resources.header);
                //Word.InlineShape shape1 = newapp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref nothing, ref nothing, ref nothing);
                //shape1.Height = 30;
                //shape1.Width = 80;
                //newapp.ActiveWindow.ActivePane.Selection.InsertAfter("青蓝医院");

                //去掉页眉的那条横线
                //newapp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleNone;
                //newapp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = false;
                //newapp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;  //  退出页眉设置

                //添加页码
                //Word.PageNumbers pns = newapp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;
                //pns.NumberStyle = Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash;
                //pns.HeadingLevelForChapter = 0;
                //pns.IncludeChapterNumber = false;
                //pns.ChapterPageSeparator = Word.WdSeparatorType.wdSeparatorHyphen;
                //pns.RestartNumberingAtSection = false;
                //pns.StartingNumber = 0;
                //object pagenmbetal = Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
                //object first = true;
                //newapp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);

                //文字设置(Selection表示当前选择集,如果当前没有选择对象,则指对光标所在处进行设置)
                newapp.Selection.Font.Size = 14;
                newapp.Selection.Font.Bold = 0;
                newapp.Selection.Font.Color = Word.WdColor.wdColorBlack;
                newapp.Selection.Font.Name = "宋体";

                //段落设置
                newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
                newapp.Selection.ParagraphFormat.LineSpacing = 20;
                newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                newapp.Selection.ParagraphFormat.FirstLineIndent = 30;
                //newdoc.Content.InsertAfter(PatientDataToFile.Properties.Resources.PreviewWords);

                //插入图片
                newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
                newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                object LinkToFile = false;
                object SaveWithDocument = true;
                object Anchor = newapp.Selection.Range;
                if (picFilePath != "")
                {
                    string picname = picFilePath;
                    newdoc.InlineShapes.AddPicture(picname, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                }
                //newdoc.InlineShapes[1].Height = 200;  //图片大小
                //newdoc.InlineShapes[1].Width = 200;
                newdoc.Content.InsertAfter("\n");
                newapp.Selection.EndKey(ref nothing, ref nothing);    //半光标移到文末
                newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                newapp.Selection.Font.Size = 10;
                newapp.Selection.TypeText("图1\n");
                newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

                //插入表格
                Word.Table table = newdoc.Tables.Add(newapp.Selection.Range, MyDGV.Rows.Count, MyDGV.Columns.Count, ref nothing, ref nothing);

                for (int i = 0; i < MyDGV.ColumnCount; i++)
                {
                    table.Cell(1, i + 1).Range.Text = MyDGV.Columns[i].HeaderText; //表头
                }

                for (int i = 0; i < MyDGV.Rows.Count - 1; i++)  //表中的数据
                {
                    for (int j = 0; j < MyDGV.Columns.Count; j++)
                    {
                        string S;
                        if (MyDGV.Rows[i].Cells[j].Value == null)
                        {
                            S = "";
                        }
                        else
                        {
                            S = MyDGV.Rows[i].Cells[j].Value.ToString();
                        }
                        table.Cell(i + 2, j + 1).Range.Text = MyDGV.Rows[i].Cells[j].Value.ToString();
                    }
                }

                if (SaveWordName != "") //保存
                {
                    try
                    {
                        newdoc.Saved = true;
                        newdoc.SaveAs(SaveWordName, 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);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                    }
                }
                object saveOption = Word.WdSaveOptions.wdSaveChanges;
                newdoc.Close(ref nothing, ref nothing, ref nothing);
                newapp.Application.Quit(ref saveOption, ref nothing, ref nothing);
            }
            catch (Exception ex)
            {
                MessageBox.Show("出错:" + ex);
            }           
        }

posted @ 2012-07-02 11:22  zhcnblog  阅读(1645)  评论(0编辑  收藏  举报