1. #region DataGridView数据显示到Excel   
  2. /// <summary>    
  3. /// 打开Excel并将DataGridView控件中数据导出到Excel   
  4. /// </summary>    
  5. /// <param name="dgv">DataGridView对象 </param>    
  6. /// <param name="isShowExcle">是否显示Excel界面 </param>    
  7. /// <remarks>   
  8. /// add com "Microsoft Excel 11.0 Object Library"   
  9. /// using Excel=Microsoft.Office.Interop.Excel;   
  10. /// </remarks>   
  11. /// <returns> </returns>    
  12. public bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle)   
  13. {   
  14.     if (dgv.Rows.Count == 0)   
  15.         return false;   
  16.     //建立Excel对象    
  17.     Excel.Application excel = new Excel.Application();   
  18.     excel.Application.Workbooks.Add(true);   
  19.     excel.Visible = isShowExcle;   
  20.     //生成字段名称    
  21.     for (int i = 0; i < dgv.ColumnCount; i++)   
  22.     {   
  23.         excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;   
  24.     }   
  25.     //填充数据    
  26.     for (int i = 0; i < dgv.RowCount - 1; i++)   
  27.     {   
  28.         for (int j = 0; j < dgv.ColumnCount; j++)   
  29.         {   
  30.             if (dgv[j, i].ValueType == typeof(string))   
  31.             {   
  32.                 excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString();   
  33.             }   
  34.             else  
  35.             {   
  36.                 excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();   
  37.             }   
  38.         }   
  39.     }   
  40.     return true;   
  41. }  
  42. #endregion   
  43. #region DateGridView导出到csv格式的Excel   
  44. /// <summary>   
  45. /// 常用方法,列之间加\t,一行一行输出,此文件其实是csv文件,不过默认可以当成Excel打开。   
  46. /// </summary>   
  47. /// <remarks>   
  48. /// using System.IO;   
  49. /// </remarks>   
  50. /// <param name="dgv"></param>   
  51. private void DataGridViewToExcel(DataGridView dgv)   
  52. {   
  53.     SaveFileDialog dlg = new SaveFileDialog();   
  54.     dlg.Filter = "Execl files (*.xls)|*.xls";   
  55.     dlg.FilterIndex = 0;   
  56.     dlg.RestoreDirectory = true;   
  57.     dlg.CreatePrompt = true;   
  58.     dlg.Title = "保存为Excel文件";   
  59.   
  60.     if (dlg.ShowDialog() == DialogResult.OK)   
  61.     {   
  62.         Stream myStream;   
  63.         myStream = dlg.OpenFile();   
  64.         StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));   
  65.         string columnTitle = "";   
  66.         try  
  67.         {   
  68.             //写入列标题   
  69.             for (int i = 0; i < dgv.ColumnCount; i++)   
  70.             {   
  71.                 if (i > 0)   
  72.                 {   
  73.                     columnTitle += "\t";   
  74.                 }   
  75.                 columnTitle += dgv.Columns[i].HeaderText;   
  76.             }   
  77.             sw.WriteLine(columnTitle);   
  78.   
  79.             //写入列内容   
  80.             for (int j = 0; j < dgv.Rows.Count; j++)   
  81.             {   
  82.                 string columnValue = "";   
  83.                 for (int k = 0; k < dgv.Columns.Count; k++)   
  84.                 {   
  85.                     if (k > 0)   
  86.                     {   
  87.                         columnValue += "\t";   
  88.                     }   
  89.                     if (dgv.Rows[j].Cells[k].Value == null)   
  90.                         columnValue += "";   
  91.                     else  
  92.                         columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();   
  93.                 }   
  94.                 sw.WriteLine(columnValue);   
  95.             }   
  96.             sw.Close();   
  97.             myStream.Close();   
  98.         }   
  99.         catch (Exception e)   
  100.         {   
  101.             MessageBox.Show(e.ToString());   
  102.         }   
  103.         finally  
  104.         {   
  105.             sw.Close();   
  106.             myStream.Close();   
  107.         }   
  108.     }   
  109.  
  110. #endregion  
  111. #region DataGridView导出到Excel,有一定的判断性   
  112. /// <summary>    
  113. ///方法,导出DataGridView中的数据到Excel文件    
  114. /// </summary>    
  115. /// <remarks>   
  116. /// add com "Microsoft Excel 11.0 Object Library"   
  117. /// using Excel=Microsoft.Office.Interop.Excel;   
  118. /// using System.Reflection;   
  119. /// </remarks>   
  120. /// <param name= "dgv"> DataGridView </param>    
  121. public static void DataGridViewToExcel(DataGridView dgv)   
  122. {  
  123.     #region   验证可操作性   
  124.   
  125.     //申明保存对话框    
  126.     SaveFileDialog dlg = new SaveFileDialog();   
  127.     //默然文件后缀    
  128.     dlg.DefaultExt = "xls ";   
  129.     //文件后缀列表    
  130.     dlg.Filter = "EXCEL文件(*.XLS)|*.xls ";   
  131.     //默然路径是系统当前路径    
  132.     dlg.InitialDirectory = Directory.GetCurrentDirectory();   
  133.     //打开保存对话框    
  134.     if (dlg.ShowDialog() == DialogResult.Cancel) return;   
  135.     //返回文件路径    
  136.     string fileNameString = dlg.FileName;   
  137.     //验证strFileName是否为空或值无效    
  138.     if (fileNameString.Trim() == " ")   
  139.     { return; }   
  140.     //定义表格内数据的行数和列数    
  141.     int rowscount = dgv.Rows.Count;   
  142.     int colscount = dgv.Columns.Count;   
  143.     //行数必须大于0    
  144.     if (rowscount <= 0)   
  145.     {   
  146.         MessageBox.Show("没有数据可供保存 ""提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);   
  147.         return;   
  148.     }   
  149.   
  150.     //列数必须大于0    
  151.     if (colscount <= 0)   
  152.     {   
  153.         MessageBox.Show("没有数据可供保存 ""提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);   
  154.         return;   
  155.     }   
  156.   
  157.     //行数不可以大于65536    
  158.     if (rowscount > 65536)   
  159.     {   
  160.         MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ""提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);   
  161.         return;   
  162.     }   
  163.   
  164.     //列数不可以大于255    
  165.     if (colscount > 255)   
  166.     {   
  167.         MessageBox.Show("数据记录行数太多,不能保存 ""提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);   
  168.         return;   
  169.     }   
  170.   
  171.     //验证以fileNameString命名的文件是否存在,如果存在删除它    
  172.     FileInfo file = new FileInfo(fileNameString);   
  173.     if (file.Exists)   
  174.     {   
  175.         try  
  176.         {   
  177.             file.Delete();   
  178.         }   
  179.         catch (Exception error)   
  180.         {   
  181.             MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);   
  182.             return;   
  183.         }   
  184.     }  
  185.     #endregion   
  186.     Excel.Application objExcel = null;   
  187.     Excel.Workbook objWorkbook = null;   
  188.     Excel.Worksheet objsheet = null;   
  189.     try  
  190.     {   
  191.         //申明对象    
  192.         objExcel = new Microsoft.Office.Interop.Excel.Application();   
  193.         objWorkbook = objExcel.Workbooks.Add(Missing.Value);   
  194.         objsheet = (Excel.Worksheet)objWorkbook.ActiveSheet;   
  195.         //设置EXCEL不可见    
  196.         objExcel.Visible = false;   
  197.   
  198.         //向Excel中写入表格的表头    
  199.         int displayColumnsCount = 1;   
  200.         for (int i = 0; i <= dgv.ColumnCount - 1; i++)   
  201.         {   
  202.             if (dgv.Columns[i].Visible == true)   
  203.             {   
  204.                 objExcel.Cells[1, displayColumnsCount] = dgv.Columns[i].HeaderText.Trim();   
  205.                 displayColumnsCount++;   
  206.             }   
  207.         }   
  208.         //设置进度条    
  209.         //tempProgressBar.Refresh();    
  210.         //tempProgressBar.Visible   =   true;    
  211.         //tempProgressBar.Minimum=1;    
  212.         //tempProgressBar.Maximum=dgv.RowCount;    
  213.         //tempProgressBar.Step=1;    
  214.         //向Excel中逐行逐列写入表格中的数据    
  215.         for (int row = 0; row <= dgv.RowCount - 1; row++)   
  216.         {   
  217.             //tempProgressBar.PerformStep();    
  218.   
  219.             displayColumnsCount = 1;   
  220.             for (int col = 0; col < colscount; col++)   
  221.             {   
  222.                 if (dgv.Columns[col].Visible == true)   
  223.                 {   
  224.                     try  
  225.                     {   
  226.                         objExcel.Cells[row + 2, displayColumnsCount] = dgv.Rows[row].Cells[col].Value.ToString().Trim();   
  227.                         displayColumnsCount++;   
  228.                     }   
  229.                     catch (Exception)   
  230.                     {   
  231.   
  232.                     }   
  233.   
  234.                 }   
  235.             }   
  236.         }   
  237.         //隐藏进度条    
  238.         //tempProgressBar.Visible   =   false;    
  239.         //保存文件    
  240.         objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value,   
  241.                 Missing.Value, Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value,   
  242.                 Missing.Value, Missing.Value);   
  243.     }   
  244.     catch (Exception error)   
  245.     {   
  246.         MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);   
  247.         return;   
  248.     }   
  249.     finally  
  250.     {   
  251.         //关闭Excel应用    
  252.         if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);   
  253.         if (objExcel.Workbooks != null) objExcel.Workbooks.Close();   
  254.         if (objExcel != null) objExcel.Quit();   
  255.   
  256.         objsheet = null;   
  257.         objWorkbook = null;   
  258.         objExcel = null;   
  259.     }   
  260.     MessageBox.Show(fileNameString + "\n\n导出完毕! ""提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);   
  261.   
  262. }  
  263. #endregion