C#Winform匯出Excel

來源:互聯網
上載者:User
View Code 
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Windows.Forms;
 using Microsoft.Office.Interop.Excel;
 namespace SaleApplication.Class
 {
     class ExportExcelOfWinform
     {
         public static bool OutToExcelFromDataGridView(string title, DataGridView dgv, bool isShowExcel)
         {
             int titleColumnSpan = 0;//標題的跨列數
             string fileName = "";//儲存的excel檔案名稱
             int columnIndex = 1;//列索引
             if (dgv.Rows.Count == 0)
                 return false;
             /*儲存對話方塊*/
             SaveFileDialog sfd = new SaveFileDialog();
             sfd.Filter = "匯出Excel(*.xls)|*.xls";
             sfd.FileName = title + DateTime.Now.ToString("yyyyMMddhhmmss");
             
             if (sfd.ShowDialog() == DialogResult.OK)
             {
                 fileName = sfd.FileName;
                 /*建立Excel對象*/
                 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                 if (excel == null)
                 {
                     MessageBox.Show("無法建立Excel對象,可能您的電腦未安裝Excel!");
                     return false;
                 }
                 try
                 {
                     excel.Application.Workbooks.Add(true);
                     excel.Visible = isShowExcel;
                     /*分析標題的跨列數*/
                     foreach (DataGridViewColumn column in dgv.Columns)
                     {
                         if (column.Visible == true)
                             titleColumnSpan++;
                     }
                     /*合并標題儲存格*/
                     Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
                     //worksheet.get_Range("A1", "C10").Merge();            
                     worksheet.get_Range(worksheet.Cells[1, 1] as Range, worksheet.Cells[1, titleColumnSpan] as Range).Merge();
                     /*產生標題*/
                     excel.Cells[1, 1] = title;
                     (excel.Cells[1, 1] as Range).HorizontalAlignment = XlHAlign.xlHAlignCenter;//標題置中
 //產生欄位名稱
                     columnIndex = 1;
                     for (int i = 0; i < dgv.ColumnCount; i++)
                     {
                         if (dgv.Columns[i].Visible == true)
                         {
                             excel.Cells[2, columnIndex] = dgv.Columns[i].HeaderText;
                             (excel.Cells[2, columnIndex] as Range).HorizontalAlignment = XlHAlign.xlHAlignCenter;//欄位置中
                             columnIndex++;
                         }
                     }
                     //填充資料              
                     for (int i = 0; i < dgv.RowCount; i++)
                     {
                         columnIndex = 1;
                         for (int j = 0; j < dgv.ColumnCount; j++)
                         {
                             if (dgv.Columns[j].Visible == true)
                             {
                                 if (dgv[j, i].ValueType == typeof(string))
                                 {
                                     excel.Cells[i + 3, columnIndex] = "'" + dgv[j, i].Value.ToString();
                                 }
                                 else
                                 {
                                     excel.Cells[i + 3, columnIndex] = dgv[j, i].Value.ToString();
                                 }
                                 (excel.Cells[i + 3, columnIndex] as Range).HorizontalAlignment = XlHAlign.xlHAlignLeft;//欄位置中
                                 columnIndex++;
                             }
                         }
                     }
                     worksheet.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);  
                 }
                 catch { }
                 finally
                 {  
                     excel.Quit(); 
                     excel = null;
                     GC.Collect();
                 }
                 //KillProcess("Excel");
                 return true;
             }
             else
             {
                 return false;
             }
         }
         private static void KillProcess(string processName)//殺死與Excel相關的進程
         {
             System.Diagnostics.Process myproc = new System.Diagnostics.Process();//得到所有開啟的進程
             try
             {
                 foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName))
                 {
                     if (!thisproc.CloseMainWindow())
                     {
                         thisproc.Kill();
                     }
                 }
             }
             catch (Exception Exc)
             {
                 throw new Exception("", Exc);
             }
         }
 
     }
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.