C# WindowsForm导出Excel表

一、写一类:
using System;
using System.Windows.Forms;
namespace WinUI.XQSF
{
/// <summary>
/// PubUtil 用于导出Grid数据。
/// </summary>
public class PubUtil
{
public PubUtil()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

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 btnExportGrid_Click(object sender, System.EventArgs e)
{
try
{
string fileName = PubUtil.ShowSaveFileDialog("Microsoft Excel Document", "Microsoft Excel|*.xls");
if(fileName != "")
{
PubUtil.ExportTo(gridView1, new DevExpress.XtraExport.ExportXlsProvider(fileName));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

你可能感兴趣的:(C++,c,Excel,C#,Microsoft)