日期:2014-05-18  浏览次数:21367 次

将datagridview的数据导出到word,还有程序中动态生成的图片!
图片的生成我已经解决了,现在就是讲datagridview中的内容和图片一起导出到word中了,请问怎么做,有些急!先谢谢了!

------解决方案--------------------

C# code

 public void ExportDataGridView(DataGridView srcDgv)
        {
            SaveFileDialog sfile = new SaveFileDialog();
            sfile.AddExtension = true;
            sfile.DefaultExt = ".doc";
            sfile.Filter = "(*.doc)|*.doc";
            if (sfile.ShowDialog() == DialogResult.OK)
            {
                object path = sfile.FileName;

                Object none = System.Reflection.Missing.Value;

                Word.Application wordApp = new Word.Application();

                Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);

                //建立表格

                Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count , srcDgv.Columns.Count, ref none, ref none);

                try
                {

                    for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
                    {

                        table.Cell(0, i + 1).Range.Text = srcDgv.Columns[i].HeaderText;

                    }

                    for (int i = 1; i < srcDgv.Rows.Count; i++)//填充数据
                    {

                        for (int j = 0; j < srcDgv.Columns.Count; j++)
                        {

                            table.Cell(i+1, j + 1).Range.Text = srcDgv[j, i - 1].Value.ToString();

                        }

                    }

                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                   document.Close(ref none, ref none, ref none);
                }

                finally
                {

                    wordApp.Quit(ref none, ref none, ref none);

                }
            }
        }