C#.NET从gridview导出Excel文件

来源:互联网 发布:淘宝如何加入公益宝贝 编辑:程序博客网 时间:2024/06/05 05:59

首先添加一个类PubUtil:

 

using System;
using System.Windows.Forms;

namespace WinUI.XQSF
{   
    public class PubUtil
    {
        public PubUtil()
        {                       
        }

        public static void ExportTo(DevExpress.XtraGrid.Views.Base.BaseView bv, DevExpress.XtraExport.IExportProvider provider)
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            DevExpress.XtraGrid.Export.BaseExportLink link = bv.CreateExportLink(provider);
            link.ExportTo(true);

            Cursor.Current = currentCursor;
        }

        public static string ShowSaveFileDialog(string title, string filter)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            string name = "导出文件";
            dlg.Title = "导出到 " + title;
            dlg.FileName = name;
            dlg.Filter = filter;
            if (dlg.ShowDialog() == DialogResult.OK) return dlg.FileName;
            return "";
        }
    }
}

 

 

然后在按钮点击事件中写如下代码:


private void barButtonItem6_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                string fileName = PubUtil.ShowSaveFileDialog("Microsoft Excel Document", "Microsoft Excel|*.xls");
                if (fileName != "")
                {
                    PubUtil.ExportTo(gridView1, new DevExpress.XtraExport.ExportXlsProvider(fileName));
                }
                MessageBox.Show("成功导出Excel文件!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

原创粉丝点击