将DataGridView控件中数据导出到Excel

/// 将DataGridView控件中数据导出到Excel
        /// </summary>
        /// <param name="gridView">DataGridView对象(没有空白行)</param>
        /// <param name="isShowExcle">是否显示Excel界面</param>
        /// <returns></returns>
        public void ExportDataGridview(DataGridView gridView, bool isShowExcle)
        {
            try
            {
                if (gridView.Rows.Count >= 1)
                {
                    //建立Excel对象
                    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                    excel.Application.Workbooks.Add(true);
                    excel.Visible = isShowExcle;
                    //生成字段名称                     for (int i = 0; i < gridView.ColumnCount; i++)                     {                         excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;                     }                     //设置列宽 A为Excel列编号                     ((Microsoft.Office.Interop.Excel.Range)excel.Columns["A", Type.Missing]).ColumnWidth = 12;                     //填充数据                     for (int i = 0; i < gridView.RowCount; i++)                     {                         for (int j = 0; j < gridView.ColumnCount; j++)                         {                             if (gridView[j, i].Value != null)                             {                                 excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();                             }                             else                                 excel.Cells[i + 2, j + 1] = "";                         }                     }                 }             }             catch (Exception ex)             {                  MessageBox.Show(ex.message.toString());             }         }
相关文章
相关标签/搜索