将datagridview导出到Word文档C# [英] Export datagridview to word document c#

查看:197
本文介绍了将datagridview导出到Word文档C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据网格导出到Word文档. 但是不是这个结果:

I'm trying to export data grid to word document. But instead of this result:

EmployeeID EmployeeName Birth Phone Address DateOfHiring Salary EmloyeeType
1           name          1     11    test    1.1.1111     1        testTy
2           name2         2     22    test    2.2.2222     2        test2Ty

我得到这样的东西:

 EmployeeID EmpoyeeName Birth   Phone   Address DateOfHiring    Salary
           EmployeeType
     1     name                                 1.1.1111

     2     name2                                2.2.2222

所有记录混合. 如何以原来的格式保存datagrid? 这是我用来执行导出的代码:

All record are mixed. How to save datagrid in the format that it originally was? Here is the code that I use to perform export:

private void ReportButton_Click(object sender, EventArgs e)
    {
        string filename = @"D:\...\AllEmployees.doc";
        ToCsV(dataGridView1, filename);
    }
private void ToCsV(DataGridView dGV, string filename)
    {
        string stOutput = "";
        // Export titles:
        string sHeaders = "";

        for (int j = 0; j < dGV.Columns.Count; j++)
            sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
        stOutput += sHeaders + "\r\n";
        // Export data.
        for (int i = 0; i < dGV.RowCount - 1; i++)
        {
            string stLine = "";
            for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
                stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";
            stOutput += stLine + "\r\n";
        }
        Encoding utf8 = Encoding.UTF8;
        byte[] output = utf8.GetBytes(stOutput);
        FileStream fs = new FileStream(filename, FileMode.Create);
        BinaryWriter bw = new BinaryWriter(fs);
        bw.Write(output, 0, output.Length); //write the encoded file
        bw.Flush();
        bw.Close();
        fs.Close();


    }

推荐答案

您可以尝试使用我的新方法将数据导出到Word(* .docx),该方法易于使用,并且可以与任何DataGridView一起100%使用,只需添加 Microsoft.Office.Interop.Word 参考并复制以下代码:

You can try my new method to export data to Word (*.docx) , it's easy to use and works 100% with any DataGridView , just add Microsoft.Office.Interop.Word reference and copy the following code :

       using Word = Microsoft.Office.Interop.Word;

       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);

             //NASSIM LOUCHANI
        }  
       }




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

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

        sfd.FileName = "export.docx";

        if (sfd.ShowDialog() == DialogResult.OK)
        {

            Export_Data_To_Word(dataGridView1, sfd.FileName); 
        }
       }

这篇关于将datagridview导出到Word文档C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆