1. 程式人生 > >GridView完美快速匯出到Excel(超強)

GridView完美快速匯出到Excel(超強)

好多人都要把Gridview的資料匯出到Excel的功能,有好多方法,最笨的就是一個一個cell讀取,然後再一個一個填充的Excel中,經過我無數次(也不是了,但確實費了很大功夫)終於實現了。

基本思路就是先把GridView全部選中,然後複製到剪貼簿,然後再貼上到excel中,就這麼簡單。

全部選中:

this.DataGridView1.SelectAll();

複製到剪貼簿:

this.DataGridView1.GetClipboardContent().GetData(DataFormats.Text) ;

貼上到Excel:

object oMissing = System.Reflection.Missing.Value;
            
try
            
{
                excel 
=new GoldPrinter.ExcelExpert.ExcelBase();
                excel.Visible 
=false;
                excel.Open();
                excel.Caption 
="查詢結果";
                Excel.Worksheet xlWorksheet 
= excel.WorkSheets.ActiveSheet;                

                System.Windows.Forms.Clipboard.SetDataObject(
"");
               
this.DataGridView1.GetClipboardContent().GetData(DataFormats.Text);
                ((Excel.Range)xlWorksheet.Cells[
11]).Select();
                xlWorksheet.Paste(oMissing, oMissing);
                System.Windows.Forms.Clipboard.SetDataObject(
"");
                

                excel.Visible 
=true;
                xlWorksheet 
=null;
                excel 
=null;
            }

            
catch
            
{
            }

結果總是報錯,難道有錯嗎,仔細檢視程式碼,發現錯誤再xlWorksheet.Paste(oMissing, oMissing)句時出現,難道不能粘切嗎,太失望了,查MSDN,沒發現什麼有價值的東西。自己試驗,發現如果剪貼簿中時純文字就不會就問題,那麼就好辦了,把該句修改Clipboard.SetText(this.DataGridView1.GetClipboardContent().GetData(DataFormats.Text).ToString()); 一切OK!收工回家。

完整程式碼:

publicvoid ExpExcel()
        
{
            
object oMissing = System.Reflection.Missing.Value;
            
try
            
{
                excel 
=new GoldPrinter.ExcelExpert.ExcelBase();
                excel.Visible 
=false;
                excel.Open();
                excel.Caption 
="查詢結果";
                Excel.Worksheet xlWorksheet 
= excel.WorkSheets.ActiveSheet;                

                System.Windows.Forms.Clipboard.SetDataObject(
"");
                Clipboard.SetText(
this.DataGridView1.GetClipboardContent().GetData(DataFormats.Text).ToString());
                ((Excel.Range)xlWorksheet.Cells[
11]).Select();
                xlWorksheet.Paste(oMissing, oMissing);
                System.Windows.Forms.Clipboard.SetDataObject(
"");               
                excel.Visible 
=true;
                xlWorksheet 
=null;
                excel 
=null;
            }

            
catch
            
{
            }

        }

說明:GoldPrinter是用了“長江支流”的金質列印通Excel操作類,在此一同表示感謝!