zoukankan      html  css  js  c++  java
  • c#-winform中DataGridView的数据实现导出excel

    首先需要引入程序集:Microsoft.Office.Interop.Excel  (如果没有引用过的需要右键添加引用再搜索就行了)

       private void button1_Click(object sender, EventArgs e)

       {
          string a = "D:" "\KKHMD.xls";
          ExportExcels(a, dataGridView1);
       }
     

       /// <summary>

       ///
       /// </summary>
       /// <param name="fileName">文件路径</param>
       /// <param name="myDGV">控件DataGridView</param>
       private void ExportExcels(string fileName, DataGridView myDGV)
       {
           string saveFileName = "";
           SaveFileDialog saveDialog = new SaveFileDialog();
           saveDialog.DefaultExt = "xls";
           saveDialog.Filter = "Excel文件|*.xls";
           saveDialog.FileName = fileName;
           saveDialog.ShowDialog();
           saveFileName = saveDialog.FileName;
           if (saveFileName.IndexOf(":") < 0) return//被点了取消
           Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
           if (xlApp == null)
           {
               MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
               return;
           }
           Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
           Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
           Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
           //写入标题
           for (int i = 0; i < myDGV.ColumnCount; i++)
           {
               worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
           }
           //写入数值
           for (int r = 0; r < myDGV.Rows.Count; r++)
           {
               for (int i = 0; i < myDGV.ColumnCount; i++)
               {
                   worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
               }
               System.Windows.Forms.Application.DoEvents();
           }
           worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
           if (saveFileName != "")
           {
               try
               {
                   workbook.Saved = true;
                   workbook.SaveCopyAs(saveFileName);
               }
               catch (Exception ex)
               {
                   MessageBox.Show("导出文件时出错,文件可能正被打开! " + ex.Message);
               }
           }
           xlApp.Quit();
           GC.Collect();//强行销毁
           MessageBox.Show("文件: " + fileName + ".xls 保存成功""信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
       }
  • 相关阅读:
    Python入门 日志打印
    Python入门 面向对象
    Python入门 更换pip源的方法
    Python入门 模块
    Python入门 函数式编程
    四月份该做的事情
    Docker入门 配置篇
    Python入门 序列章
    Python入门 值内存管理与所有的关键字
    论操作系统的IO
  • 原文地址:https://www.cnblogs.com/kcwang/p/14966508.html
Copyright © 2011-2022 走看看