将datagridview导出到现有单词doc中的特定位置

时间:2015-03-31 16:44:03

标签: c# datagridview ms-word

我正在尝试构建一个有一个datagridview的程序。最初我只是想打印这个网格,但后来决定我想要标题,预先写好的文本等等,我 想到 最简单的方法就是将它导出到一个word文档。

我的网格没有填充任何数据库或任何内容,它会根据程序中选择的选项填充。因此,您单击几个选项并填写几个价格,然后单击一个按钮,使用dataGridView1.Rows.Add();选项将添加到另一个选项卡页面上的网格中。

现在,我想将网格导出到word doc。我在这里经历过很多问题,曾经在msdn和所有常见的地方,但我找不到我想要的东西。我在msdn上发现了一个tut,它打开了一个新的doc,插入了标题和表格等,但我唯一可以使用的是

private void Export_Click(object sender, EventArgs e)
    {
        object oMissing = Missing.Value;
        object oEndOfDoc = "\\endofdoc";

        //Start Word and create a new document.
        Word._Application oWord;
        Word._Document oDoc;
        oWord = new Word.Application();
        oWord.Visible = true;
        oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
            ref oMissing, ref oMissing);
    }

但我不明白如何从网格导出?

1 个答案:

答案 0 :(得分:0)

最后管理它 - 这是我对任何有兴趣的人最终得到的结果;

Word._Application oWord;
                Word._Document oDoc;
                oWord = new Word.Application();
                oWord.Visible = true;
                object oTemplate = "C:/Users/Sean/Documents/Custom Office Templates/BMW Invoice.dotx";
                oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,
                    ref oMissing, ref oMissing);
                Object start = Type.Missing;
                Object end = Type.Missing;
                object missing = System.Type.Missing;
                Microsoft.Office.Interop.Word.Range rng = oDoc.Range(ref start, ref end);
                Microsoft.Office.Interop.Word.Table tbl = oDoc.Tables.Add(rng, dataGridView1.Rows.Count, dataGridView1.Columns.Count, ref oMissing, ref oMissing);
                Microsoft.Office.Interop.Word.Row newRow = oDoc.Tables[1].Rows.Add(ref missing);
                newRow.Range.Font.Bold = 0;
                newRow.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                tbl.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                tbl.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
                tbl.Cell(0, 0).WordWrap = false;
                tbl.Cell(0, 0).FitText = true;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (i == dataGridView1.Rows.Count - 1)
                        MessageBox.Show("Successfully Exported");
                    else
                    {
                        for (int j = 0; j < dataGridView1.Columns.Count; j++)
                        {

                            tbl.Cell(i + 1, j + 1).Range.Text = dataGridView1.Rows[i].Cells[j].Value.ToString();
                        }
                    }
                }
相关问题