1. 程式人生 > >把datagridview中的資料匯入到excel中

把datagridview中的資料匯入到excel中

一定要引入一個dll檔案,這個檔案叫做Interop.Microsoft.Office.Interop.Excel.dll

步驟:新增引用->瀏覽->新增Interop.Microsoft.Office.Interop.Excel.dll即可。

下面的步驟是網上的。不需要,也許是另外一種方法或者是因為Office excel安裝正常不需要上面的步驟可以直接從COM引用吧。管他呢,成功就好。

步驟:右鍵引用->com->microsoft 11.1 object Library->確定

using using Microsoft.Office.Interop.Excel;

 /// <summary>
        /// Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExcel_Click(IButtonInfo info)
        {
            if (DgvInspection.Rows.Count == 0)
            {
                CountdownMsgFrm.ShowMsg("無法進行匯出,請確定您已經查詢出資料!");
                return;
            }
            ExportExcel("檢查檢驗Excel列表"+DateTime.Now.ToString("yyyy-MM-dd")+"", DgvInspection);
        }

/// <summary>
        /// 匯出到Excel方法
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="myDGV"></param>
        private void ExportExcel(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 (Microsoft.Office.Interop.cmbxType.Text != "Notification")
            //{
            //    Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);
            //    rg.NumberFormat = "00000000";