DataTable數據導入到Excel 引用Microsoft Office 12.0 Object Library和 Microsoft Excel 14.0 Object Library 並且需要注意的問題


        /// <summary>
        /// 將DataTalbe導出到Excel中
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="ProjectName">生成的Excel的Sheet的名字</param>
        /// <param name="filePath">保存的路徑</param>
        public static void Export(System.Data.DataTable dt, string filePath)
        {
            if (dt == null)
            {
                throw new Exception("數據表中無數據");
            }
            int eRowIndex = 1;
            int eColIndex = 1;
            int cols = dt.Columns.Count;
            int rows = dt.Rows.Count;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
            try
            {
                //列名的處理
                for (int i = 0; i < cols; i++)
                {
                    xlApp.Cells[eRowIndex, eColIndex] = dt.Columns[i].ColumnName;
                    eColIndex++;
                }
                //列名加粗顯示
                xlApp.get_Range(xlApp.Cells[eRowIndex, 1], xlApp.Cells[eRowIndex, cols]).Font.Bold = true;
                xlApp.get_Range(xlApp.Cells[eRowIndex, 1], xlApp.Cells[rows + 1, cols]).Font.Name = "Arial";
                xlApp.get_Range(xlApp.Cells[eRowIndex, 1], xlApp.Cells[rows + 1, cols]).Font.Size = "10";
                eRowIndex++;

                for (int i = 0; i < rows; i++)
                {
                    eColIndex = 1;
                    for (int j = 0; j < cols; j++)
                    {
                        xlApp.Cells[eRowIndex, eColIndex] = dt.Rows[i][j].ToString();
                        eColIndex++;
                    }
                    eRowIndex++;
                }
                //控制單元格中的內容。
                xlApp.Cells.EntireColumn.AutoFit();

                xlApp.DisplayAlerts = false;
                xlBook.SaveCopyAs(filePath);
                xlApp.Workbooks.Close();
            }
            catch
            {
                throw;
            }
            finally
            {
                xlApp.Quit();
                //殺掉Excel進程。
                GC.Collect();
            }
        }

 注意:using Microsoft.Office.Interop.Excel;  VS2010 下 添加引用  COM選項中找Microsoft Office 12.0 Object Library  Microsoft Excel 14.0 Object Library

引用目錄下出現Microsoft.Office.Core     Microsoft.Office.Interop.Excel

如果代碼中出現  Excel.ApplicationClass()無法互嵌套操作類型 請改用適用的接口 

把引用的Microsoft.Office.Interop.Excel 右擊屬性 嵌入互操作類型改為false即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM