当前位置:  开发笔记 > 编程语言 > 正文

通过C#.NET在Word中创建动态表

如何解决《通过C#.NET在Word中创建动态表》经验,为你挑选了1个好方法。

我有一个C#应用程序,我想为程序实现一个逻辑,它将打开word文档并转到页面中的某个位置并创建一个表并将值放入其中.任何人都可以告诉我如何实现这一点.我正在使用Visual Studio 2005



1> Gary Kindel..:

以下是将datagridview复制到word表的代码:

引用的Microsoft.Office.Interop.Word C:\ Program Files文件(x86)的\微软的Visual Studio 10.0\Visual Studio工具用于Office\PIA\OFFICE12\Microsoft.Office.Interop.Word.dll

using word = Microsoft.Office.Interop.Word;    
public static void ExportToWord(DataGridView dgv)
                {
                    SendMessage("Opening Word");

                    word.ApplicationClass word = null;



      word.Document doc = null;
            object oMissing = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ 
            try
            {
                word = new word.ApplicationClass();
                word.Visible = true;
                doc = word.Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing);
            }
            catch (Exception ex)
            {
                ErrorLog(ex);
            }
            finally
            {
            }
            if (word != null && doc != null)
            {
                word.Table newTable;
                word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                newTable = doc.Tables.Add(wrdRng, 1, dgv.Columns.Count-1, ref oMissing, ref oMissing);
                newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                newTable.AllowAutoFit = true;

                foreach (DataGridViewCell cell in dgv.Rows[0].Cells)
                {
                    newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = dgv.Columns[cell.ColumnIndex].Name;

                }
                newTable.Rows.Add();

                foreach (DataGridViewRow row in dgv.Rows)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = cell.Value.ToString();                      
                    }
                    newTable.Rows.Add();
                }                                              
            }

        }

推荐阅读
罗文彬2502852027
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有