zoukankan      html  css  js  c++  java
  • WinForm下DataGridView导出Excel的实现

    WinForm下DataGridView导出Excel的实现
     
    1.说明:导出的效率说不上很高,但至少是可以接收的.参考网上很多高效导出Excel的方法,实现到时能够实现的,导出速度也很快,不过缺陷在与不能很好的进行单元格的格式化,比如上图中的"拼音码"字段中的值"000000000012120",在导出后就显示"12120",挺郁闷的!o(∩_∩)o,废话不说了,进入正题.......
    2.首先添加Excel引用
     
    3.实现代码

    /// <summary>
            /// DataGridView导出Excel
            /// </summary>
            /// <param name="strCaption">Excel文件中的标题</param>
            /// <param name="myDGV">DataGridView 控件</param>
            /// <returns>0:成功;1:DataGridView中无记录;2:Excel无法启动;9999:异常错误</returns>
            private int ExportExcel(string strCaption, DataGridView myDGV)
            {
                int result = 9999;
                // 列索引,行索引,总列数,总行数
                int ColIndex = 0;
                int RowIndex = 0;
                int ColCount = myDGV.ColumnCount;
                int RowCount = myDGV.RowCount;
    
                if (myDGV.RowCount == 0)
                {
                    result = 1;
                }
    
                // 创建Excel对象
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                if (xlApp == null)
                {
                    result = 2;
                }
                try
                {
                    // 创建Excel工作薄
                    Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
                    Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];
                    // 设置标题
                    Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //标题所占的单元格数与DataGridView中的列数相同
                    range.MergeCells = true;
                    xlApp.ActiveCell.FormulaR1C1 = strCaption;
                    xlApp.ActiveCell.Font.Size = 20;
                    xlApp.ActiveCell.Font.Bold = true;
                    xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
                    // 创建缓存数据
                    object[,] objData = new object[RowCount + 1, ColCount];
                    //获取列标题
                    foreach (DataGridViewColumn col in myDGV.Columns)
                    {
                        objData[RowIndex, ColIndex++] = col.HeaderText;
                    }
                    // 获取数据
                    for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
                    {
                        for (ColIndex = 0; ColIndex < ColCount; ColIndex++)
                        {
                            if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string) 
                                || myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓存时在该内容前加入" ";
                            {
                                objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;
                            }
                            else
                            {
                                objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;
                            }
                        }
                        System.Windows.Forms.Application.DoEvents();
                    }
                    // 写入Excel
                    range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]);
                    range.Value2 = objData;
    
                    //保存
                    xlBook.Saved = true;
                    xlBook.SaveCopyAs("C://测试" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
                    //返回值
                    result = 0;
                }
                catch (Exception err)
                {
                    result = 9999;
                }
                finally
                {
                    xlApp.Quit();
                    GC.Collect(); //强制回收
                }
                return result;
            } 

    4.调用方法(上图中"生成Excel文件"按钮的onClick事件)

            private void button4_Click(object sender, EventArgs e)
            {           
                int result = this.ExportExcel("测试", this.dataGridView1); //this.dataGridView1:DataGridView控件
                MessageBox.Show(result.ToString());
            }

     

    引用Microsoft.Office.Interop.Excel出现的问题

    08-06-11 14:41   View:5700


    操作背景:asp.net操作Excel

    出现问题:在本地添加引用(com):Microsoft Office 11.0 Object Library,并写好程序调试正常,部署到服务器时,出现异常 Excel.Application不是对象.

    初步诊断:服务器没有安装Excel组件

    第一步尝试解决:对服务器安装Excel等Office组件,进一步测试程序:失败!

    第二步尝试解决:将Excel.exe生成Interop.Excel.dll,然后用sdk引用该Dll,编译成功,测试程序:成功!

    原因:本地引用的com不会在程序的bin目录生成dll文件,而程序是根据路径在寻找dll的.部署到服务器上时,假如Excel等dll与本地路径不一致,将会抛出异常,定义的Excel对象肯定是不存在的.

    具体方法:

    1、如何生成Interop.Excel.dll?

         进入你的visual studio的sdk下的bin目录,找到TlbImp.exe文件,如果没有,请用光盘安装此文件,详细说明请参照MSDN。
         命令行(cmd)进入bin目录,运行TlbImp /out:Interop.Excel.dll Office安装目录+Excel.exe

         此时很可能会报错:TlbImp   error:   Unable   to   locate   input   type   library:   'c:/program files/mcrosoft offi  
      ce/office/EXCEL.EXE'
         此问题很有可能是TlbImp的bug,不支持空格式的路径;(具体原因不明)不要紧,将Excel.exe拷贝入bin目录,直接运行TlbImp /out:Interop.Excel.dll Excel.exe,提示“Type library imported to Interop.Excel.dll路径”

         在bin目录下找到Interop.Excel.dll文件。在你的visual studio里将其引用即可。

    2、如果是excel2000或excel2002怎么办?

      如果是Excel2000,则将Excel.exe改成Excel9.olb
      Excel2002同2003

    3、各种版本的引用组件参数如下:

    文件/版本 Interop.Excel.dll Interop.Office.dll Interop.VBIDE.dll 添加引用/COM组件
    2000 V1.3.0.0 V2.1.0.0 V5.3.0.0 Microsoft Excel 9.0 Object Library(EXCEL9.OLB)
    2002(XP) V1.4.0.0 V2.2.0.0 V5.3.0.0 Microsoft Excel 10.0 Object Library(Excel.EXE文件)
    2003 V1.5.0.0 V2.3.0.0 V5.3.0.0 Microsoft Excel 11.0 Object Library(Excel.EXE文件)
  • 相关阅读:
    Linux服务器通过rz/sz轻松上传下载文件
    Linux卸载系统自带的JDK
    汉语-词语:恒等
    汉语-词语:女人
    汉语-词语:长远
    汉语-词语:长久
    汉语-词语:短暂
    汉语-词语:当下
    汉语-词语:漫长
    中药:小麦
  • 原文地址:https://www.cnblogs.com/huyong/p/2685632.html
Copyright © 2011-2022 走看看