DataGridView 에서 Excel 로 내 보 내 는 세 가지 방법

13984 단어 datagridview
출처
#region DataGridView     Excel

/// <summary> 

///   Excel  DataGridView        Excel

/// </summary> 

/// <param name="dgv">DataGridView   </param> 

/// <param name="isShowExcle">    Excel   </param> 

/// <remarks>

/// add com "Microsoft Excel 11.0 Object Library"

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

/// </remarks>

/// <returns> </returns> 

public bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle)

{

    if (dgv.Rows.Count == 0)

        return false;

    //  Excel   

    Excel.Application excel = new Excel.Application();

    excel.Application.Workbooks.Add(true);

    excel.Visible = isShowExcle;

    //       

    for (int i = 0; i < dgv.ColumnCount; i++)

    {

        excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;

    }

    //     

    for (int i = 0; i < dgv.RowCount - 1; i++)

    {

        for (int j = 0; j < dgv.ColumnCount; j++)

        {

            if (dgv[j, i].ValueType == typeof(string))

            {

                excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString();

            }

            else

            {

                excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();

            }

        }

    }

    return true;

}

#endregion 



#region DateGridView   csv   Excel

/// <summary>

///     ,    \t,      ,      csv  ,        Excel  。

/// </summary>

/// <remarks>

/// using System.IO;

/// </remarks>

/// <param name="dgv"></param>

private void DataGridViewToExcel(DataGridView dgv)

{

    SaveFileDialog dlg = new SaveFileDialog();

    dlg.Filter = "Execl files (*.xls)|*.xls";

    dlg.FilterIndex = 0;

    dlg.RestoreDirectory = true;

    dlg.CreatePrompt = true;

    dlg.Title = "   Excel  ";



    if (dlg.ShowDialog() == DialogResult.OK)

    {

        Stream myStream;

        myStream = dlg.OpenFile();

        StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));

        string columnTitle = "";

        try

        {

            //     

            for (int i = 0; i < dgv.ColumnCount; i++)

            {

                if (i > 0)

                {

                    columnTitle += "\t";

                }

                columnTitle += dgv.Columns[i].HeaderText;

            }

            sw.WriteLine(columnTitle);



            //     

            for (int j = 0; j < dgv.Rows.Count; j++)

            {

                string columnValue = "";

                for (int k = 0; k < dgv.Columns.Count; k++)

                {

                    if (k > 0)

                    {

                        columnValue += "\t";

                    }

                    if (dgv.Rows[j].Cells[k].Value == null)

                        columnValue += "";

                    else

                        columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();

                }

                sw.WriteLine(columnValue);

            }

            sw.Close();

            myStream.Close();

        }

        catch (Exception e)

        {

            MessageBox.Show(e.ToString());

        }

        finally

        {

            sw.Close();

            myStream.Close();

        }

    }

} 

#endregion



#region DataGridView   Excel,       

/// <summary> 

///  ,  DataGridView     Excel   

/// </summary> 

/// <remarks>

/// add com "Microsoft Excel 11.0 Object Library"

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

/// using System.Reflection;

/// </remarks>

/// <param name= "dgv"> DataGridView </param> 

public static void DataGridViewToExcel(DataGridView dgv)

{





    #region         



    //        

    SaveFileDialog dlg = new SaveFileDialog();

    //       

    dlg.DefaultExt = "xls ";

    //       

    dlg.Filter = "EXCEL  (*.XLS)|*.xls ";

    //            

    dlg.InitialDirectory = Directory.GetCurrentDirectory();

    //        

    if (dlg.ShowDialog() == DialogResult.Cancel) return;

    //       

    string fileNameString = dlg.FileName;

    //  strFileName         

    if (fileNameString.Trim() == " ")

    { return; }

    //              

    int rowscount = dgv.Rows.Count;

    int colscount = dgv.Columns.Count;

    //      0 

    if (rowscount <= 0)

    {

        MessageBox.Show("         ", "   ", MessageBoxButtons.OK, MessageBoxIcon.Information);

        return;

    }



    //      0 

    if (colscount <= 0)

    {

        MessageBox.Show("         ", "   ", MessageBoxButtons.OK, MessageBoxIcon.Information);

        return;

    }



    //       65536 

    if (rowscount > 65536)

    {

        MessageBox.Show("       (      65536 ),     ", "   ", MessageBoxButtons.OK, MessageBoxIcon.Information);

        return;

    }



    //       255 

    if (colscount > 255)

    {

        MessageBox.Show("        ,     ", "   ", MessageBoxButtons.OK, MessageBoxIcon.Information);

        return;

    }



    //   fileNameString         ,        

    FileInfo file = new FileInfo(fileNameString);

    if (file.Exists)

    {

        try

        {

            file.Delete();

        }

        catch (Exception error)

        {

            MessageBox.Show(error.Message, "     ", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            return;

        }

    }

    #endregion

    Excel.Application objExcel = null;

    Excel.Workbook objWorkbook = null;

    Excel.Worksheet objsheet = null;

    try

    {

        //     

        objExcel = new Microsoft.Office.Interop.Excel.Application();

        objWorkbook = objExcel.Workbooks.Add(Missing.Value);

        objsheet = (Excel.Worksheet)objWorkbook.ActiveSheet;

        //  EXCEL    

        objExcel.Visible = false;



        // Excel         

        int displayColumnsCount = 1;

        for (int i = 0; i <= dgv.ColumnCount - 1; i++)

        {

            if (dgv.Columns[i].Visible == true)

            {

                objExcel.Cells[1, displayColumnsCount] = dgv.Columns[i].HeaderText.Trim();

                displayColumnsCount++;

            }

        }

        //      

        //tempProgressBar.Refresh(); 

        //tempProgressBar.Visible   =   true; 

        //tempProgressBar.Minimum=1; 

        //tempProgressBar.Maximum=dgv.RowCount; 

        //tempProgressBar.Step=1; 

        // Excel              

        for (int row = 0; row <= dgv.RowCount - 1; row++)

        {

            //tempProgressBar.PerformStep(); 



            displayColumnsCount = 1;

            for (int col = 0; col < colscount; col++)

            {

                if (dgv.Columns[col].Visible == true)

                {

                    try

                    {

                        objExcel.Cells[row + 2, displayColumnsCount] = dgv.Rows[row].Cells[col].Value.ToString().Trim();

                        displayColumnsCount++;

                    }

                    catch (Exception)

                    {



                    }



                }

            }

        }

        //      

        //tempProgressBar.Visible   =   false; 

        //     

        objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value,

                Missing.Value, Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value,

                Missing.Value, Missing.Value);

    }

    catch (Exception error)

    {

        MessageBox.Show(error.Message, "   ", MessageBoxButtons.OK, MessageBoxIcon.Warning);

        return;

    }

    finally

    {

        //  Excel   

        if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);

        if (objExcel.Workbooks != null) objExcel.Workbooks.Close();

        if (objExcel != null) objExcel.Quit();



        objsheet = null;

        objWorkbook = null;

        objExcel = null;

    }

    MessageBox.Show(fileNameString + "

! "
, " ", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

좋은 웹페이지 즐겨찾기