将数据从datagrid保存到Microsoft Word文档中

时间:2017-04-03 11:41:07

标签: c# datagridview ms-word save

我有5张表Tables

当我按下按钮时,dataGrid中的数据必须保存为Microsoft doc。我试试这段代码

public void Export_Data_To_Word(DataGridView DGV, string filename)
{
    if (DGV.Rows.Count != 0)
    {
        int RowCount = DGV.Rows.Count;
        int ColumnCount = DGV.Columns.Count;
        Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];

        //add rows
        int r = 0;
        for (int c = 0; c <= ColumnCount - 1; c++)
        {
            for (r = 0; r <= RowCount - 1; r++)
            {
                DataArray[r, c] = DGV.Rows[r].Cells[c].Value;
            } //end row loop
        } //end column loop

        Word.Document oDoc = new Word.Document();
        oDoc.Application.Visible = true;

        //page orintation
        oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
        dynamic oRange = oDoc.Content.Application.Selection.Range;
        string oTemp = "";
        for (r = 0; r <= RowCount - 1; r++)
        {
            for (int c = 0; c <= ColumnCount - 1; c++)
            {
                oTemp = oTemp + DataArray[r, c] + "\t";
            }
        }

        //table format
        oRange.Text = oTemp;
        object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;
        object ApplyBorders = true;
        object AutoFit = true;
        object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;
        oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
                              Type.Missing, Type.Missing, ref ApplyBorders,
                              Type.Missing, Type.Missing, Type.Missing,
                              Type.Missing, Type.Missing, Type.Missing,
                              Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);

        oRange.Select();
        oDoc.Application.Selection.Tables[1].Select();
        oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
        oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;
        oDoc.Application.Selection.Tables[1].Rows[1].Select();
        oDoc.Application.Selection.InsertRowsAbove(1);
        oDoc.Application.Selection.Tables[1].Rows[1].Select();

        //header row style
        oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;
        oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma";
        oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;

        //add header row manually
        for (int c = 0; c <= ColumnCount - 1; c++)
        {
            oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;
        }

        //table style 
        oDoc.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5");
        oDoc.Application.Selection.Tables[1].Rows[1].Select();
        oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

        //header text
        foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
        {
            Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
            headerRange.Text = "your header text";
            headerRange.Font.Size = 16;
            headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
        }
        //save the file
        oDoc.SaveAs2(filename);
    }
}

private void button1_Click(object sender, EventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Word Documents (*.docx)|*.docx";
    sfd.FileName = "your_bisness.docx";
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        Export_Data_To_Word(dataGridView1, sfd.FileName);
    }
}

当我按下按钮保存时,我得到了这个Result

文档在程序工作时运行。我只需要保存文档(不要打开它)。如何在没有边框的图像表上将所有5个表(dataGrid1,2,3,4,5)保存在一个带有表边框的文档中。

请帮忙

1 个答案:

答案 0 :(得分:0)

这需要付出一些努力,但最好更好地构建代码。问题是:导出完成的Export_Data_To_Word只能通过dataGrid1调用。完成后,文件将被保存。也许您可以尝试创建一个打开文档的方法,另一种添加数据网格的方法,以及保存文档的最终方法。

这样的事情:

准备导出文档的方法:

public Word.Document GetPreparedDocument()
{
    Word.Document oDoc = new Word.Document();
    oDoc.Application.Visible = true;

    //page orintation
    oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;

    //additional page setup

    return oDoc;
}

插入表格的方法,请注意它不使用文件名而是使用文档:

public void Export_Data_To_Word(DataGridView DGV, Word.Document oDoc)
{
   //alter document here
   //I don't have time to write this for you,
   //Keep in mind that you'll need to keep track of the table indices.
}

保存例程:

public void Save(Word.Document oDoc, string fileName)
{
     //extra finalizrs
     oDoc.SaveAs2(fileName);
}  

并称呼他们:

private void button1_Click(object sender, EventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();

    sfd.Filter = "Word Documents (*.docx)|*.docx";
    sfd.FileName = "your_bisness.docx";

    if (sfd.ShowDialog() == DialogResult.OK)
    {
        Word.Document oDoc = GetPreparedDocument();

        Export_Data_To_Word(dataGridView1, oDoc );
        Export_Data_To_Word(dataGridView2, oDoc );
        Export_Data_To_Word(dataGridView3, oDoc );
        Export_Data_To_Word(dataGridView4, oDoc );
        Export_Data_To_Word(dataGridView5, oDoc );

        Save(oDoc,sfd.FileName);
    }
}

我希望这会有所帮助。

作为替代方案,快速修复

您也可以坚持原始代码,但改变Export_Data_To_Word,以便处理数据网格转换。

//note don't use DGV anymore, dataGridView1 till dataGridView5 are available
public void Export_Data_To_Word(Word.Document oDoc)
{
    //your code (still sort on time)

    //prepare doc like you did

    //The difference is this:
    //insert table for dataGridView1
    //insert table for dataGridView2 
    //insert table for dataGridView3
    //insert table for dataGridView4
    //insert table for dataGridView5
    //For every insert you'll have to do the selection,
    //table conversion etc. so it's going to be a lot of code
    //therefore it's best to try to study a bit about member
    //variables first

    //save file like you did
}