将datagridview导出到word文档c#

时间:2015-04-19 11:44:13

标签: c# winforms datagridview ms-word

我试图将数据网格导出到word文档。 但不是这个结果:

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

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

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


    }

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

使用代码导出gridview数据。

 protected void btnexportreport_Click(object sender, EventArgs e)
            {
                ExportGridToExcel();
            }

            private void ExportGridToExcel()
            {

                Response.AddHeader("content-disposition", "attachment;filename=Excelsheet" + DateTime.Now.Ticks.ToString() + ".xls");
                Response.Charset = "";
                Response.ContentType = "application/vnd.xls";
                StringWriter StringWriter = new System.IO.StringWriter();
                HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

                gvdisplay.RenderControl(HtmlTextWriter);


                Response.Write(StringWriter.ToString());
                Response.End();
                Response.Clear();


            }

答案 2 :(得分:0)

此导出gridview数据的代码

namespace WindowsFormsApplication1
{
    using System;
    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    using Microsoft.Office.Interop.Excel;

    using Application = Microsoft.Office.Interop.Excel.Application;

    public partial class Form1 : Form
    {
        private Application xlExcel;

        private Workbook xlWorkBook;

        public Form1()
        {
            this.InitializeComponent();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                this.QuitExcel();
                this.xlExcel = new Application { Visible = false };
                this.xlWorkBook = this.xlExcel.Workbooks.Add(Missing.Value);

                // Copy contents of grid into clipboard, open new instance of excel, a new workbook and sheet,
                // paste clipboard contents into new sheet.
                this.CopyGrid();

                var xlWorkSheet = (Worksheet)this.xlWorkBook.Worksheets.Item[1];

                try
                {
                    var cr = (Range)xlWorkSheet.Cells[1, 1];

                    try
                    {
                        cr.Select();
                        xlWorkSheet.PasteSpecial(cr, NoHTMLFormatting: true);
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(cr);
                    }

                    this.xlWorkBook.SaveAs(Path.Combine(Path.GetTempPath(), "ItemUpdate.xls"), XlFileFormat.xlExcel5);
                }
                finally
                {
                    Marshal.ReleaseComObject(xlWorkSheet);
                }

                MessageBox.Show("File Save Successful", "Information", MessageBoxButtons.OK);

                // If box is checked, show the exported file. Otherwise quit Excel.
                if (this.checkBox1.Checked)
                {
                    this.xlExcel.Visible = true;
                }
                else
                {
                    this.QuitExcel();
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            // Set the Selection Mode back to Cell Select to avoid conflict with sorting mode.
            this.dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.QuitExcel();
        }

        private void QuitExcel()
        {
            if (this.xlWorkBook != null)
            {
                try
                {
                    this.xlWorkBook.Close();
                    Marshal.ReleaseComObject(this.xlWorkBook);
                }
                catch (COMException)
                {
                }

                this.xlWorkBook = null;
            }

            if (this.xlExcel != null)
            {
                try
                {
                    this.xlExcel.Quit();
                    Marshal.ReleaseComObject(this.xlExcel);
                }
                catch (COMException)
                {
                }

                this.xlExcel = null;
            }
        }

        private void CopyGrid()
        {
            // I'm making this up...
            this.dataGridView1.SelectAll();

            var data = this.dataGridView1.GetClipboardContent();

            if (data != null)
            {
                Clipboard.SetDataObject(data, true);
            }
        }
    }
}

试试这个link

this also

答案 3 :(得分:0)

您可以尝试我的方法将数据导出到Excel(* .Xlsx),它易于使用并且可以100%使用任何DataGridView,只需复制以下代码:

    using Excel = Microsoft.Office.Interop.Excel;
    using Microsoft.Office.Interop.Excel;
    using System.Reflection;

    public void Export_DataGridView_To_Excel(DataGridView DGV, string filename)
    {
        string[] Alphabit = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                              "N", "O","P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

        string Range_Letter = Alphabit[DGV.Columns.Count];
        string Range_Row = (DGV.Rows.Count + 1).ToString();

        if (File.Exists(filename))
        {
            File.Delete(filename);
        }

        Excel.Application oApp;
        Excel.Worksheet oSheet;
        Excel.Workbook oBook;

        oApp = new Excel.Application();
        oBook = oApp.Workbooks.Add();
        oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);


        for (int x = 0; x < DGV.Columns.Count; x++)
        {
            // creating Columns :
            oSheet.Cells[1, x + 2] = DGV.Columns[x].HeaderText;
        }


        for (int i = 0; i < DGV.Columns.Count; i++)
        {
            for (int j = 0; j < DGV.Rows.Count; j++)
            {
                // creating rows :
                oSheet.Cells[j + 2, i + 2] = DGV.Rows[j].Cells[i].Value;
            }
        }

        //Add some formatting
        Range rng1 = oSheet.get_Range("B1", Range_Letter + "1");
        rng1.Font.Size = 14;
        rng1.Font.Bold = true;
        rng1.Cells.Borders.LineStyle = XlLineStyle.xlDouble;
        rng1.Cells.Borders.Color = System.Drawing.Color.DeepSkyBlue;
        rng1.Font.Color = System.Drawing.Color.Black;
        rng1.HorizontalAlignment = XlHAlign.xlHAlignCenter;
        rng1.Interior.Color = System.Drawing.Color.LightGray;

        Range rng2 = oSheet.get_Range("B2", Range_Letter + Range_Row);
        rng2.WrapText = false;
        rng2.Font.Size = 12;
        rng2.Cells.Borders.LineStyle = XlLineStyle.xlContinuous;
        rng2.Cells.Borders.Color = System.Drawing.Color.DeepSkyBlue;
        rng2.VerticalAlignment = XlVAlign.xlVAlignCenter;
        rng2.Interior.Color = System.Drawing.Color.Azure;
        rng2.EntireColumn.AutoFit();
        rng2.EntireRow.AutoFit();

        //Add a header row
        oSheet.get_Range("B1", Range_Letter + "2").EntireRow.Insert(XlInsertShiftDirection.xlShiftDown, Missing.Value);
        oSheet.Cells[1, 3] = "List of : list title ";
        Range rng3 = oSheet.get_Range("B1", Range_Letter + "2");
        rng3.Merge(Missing.Value);
        rng3.Font.Size = 16;
        rng3.Font.Color = System.Drawing.Color.Blue;
        rng3.Font.Bold = true;
        rng3.VerticalAlignment = XlVAlign.xlVAlignCenter;
        rng3.Interior.Color = System.Drawing.Color.LightSkyBlue;


        oBook.SaveAs(filename);
        oBook.Close();
        oApp.Quit();
     // NASSIM LOUCHANI
    }

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

      sfd.Title = "Export To Excel";
      sfd.Filter = "To Excel (Xlsx)|*.xlsx";
      sfd.FileName = "your document name";

        if (sfd.ShowDialog() == DialogResult.OK)
        {
             AED.Export_DataGridView_To_Excel(dataGridView,sfd.FileName);
        }
    }

谢谢。

相关问题