天天看點

WinForm下DataGridView導出Excel的實作引用Microsoft.Office.Interop.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());

        }

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檔案,如果沒有,請用CD光牒安裝此檔案,詳細說明請參照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

Microsoft Excel 10.0 Object Library(Excel.EXE檔案)

2003

V1.5.0.0

V2.3.0.0

Microsoft Excel 11.0 Object Library(Excel.EXE檔案)

 本文轉自yonghu86 51CTO部落格,原文連結:http://blog.51cto.com/yonghu/1321394,如需轉載請自行聯系原作者