天天看點

C#將winform程式導出到Excel

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop;


namespace AdvancedFiltration
{
    class dataSetToExcel
    {
        /// <summary>
        /// DataSet集合輸出到Excel中
        /// </summary>
        /// <param name="dataSet">DataSet集合</param>
        /// <param name="isShowExcle">是否打開Excel檔案,true or false</param>
        /// <returns>,輸出成功,則為true</returns>
        public bool DataSetToExcel(DataSet dataSet, bool isShowExcle)
        {
            DataTable dataTable = dataSet.Tables[0];
            int rowNumber = dataTable.Rows.Count;//總行數
            int columnNumber = dataTable.Columns.Count;//總列數

            if (rowNumber == 0)
            {
                MessageBox.Show("沒有任何資料可以導入到Excel檔案!");
                return false;
            }

            //建立Excel對象 
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(true);//建立一個工作簿
            excel.Visible = isShowExcle;//是否打開該Excel檔案 

            //填充資料 
            for (int c = 0; c < rowNumber; c++)
            {
                for (int j = 0; j < columnNumber; j++)
                {
                    excel.Cells[c + 1, j + 1] = dataTable.Rows[c].ItemArray[j];
                }
            }

            return true;
        }
    }
}

           

ERROR:命名空間"Microsoft"中不存在類型或命名空間名稱"Office"(是否缺少程式引用?)

添加引用 —— COM —— Microsoft Office14.0 Object Library 和 Microsoft Excel 14.0 Object Library