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!收工回家。

完整代码:

 

public   void  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操作类,在此一同表示感谢!

你可能感兴趣的:(GridView完美快速导出到Excel(超强))