第一种导出方法
/**//// <summary>
/// 将DataGridView控件中数据导出到Excel
/// </summary>
/// <param name="gridView">DataGridView对象</param>
/// <returns></returns>
public bool ExportDataGridview(DataGridViewX gridView )
{
if (gridView.Rows.Count == 0)
return false;
//建立Excel对象
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;
//生成字段名称
for (int i = 0; i < gridView.ColumnCount; i++)
{
excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < gridView.RowCount - 1; i++)
{
for (int j = 0; j < gridView.ColumnCount; j++)
{
if (gridView[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + gridView[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
}
}
}
return true;
}
/**//// <summary>
/// 将DataGridView控件中数据导出到Excel
/// </summary>
/// <param name="gridView">DataGridView对象</param>
/// <returns></returns>
public bool ExportDataGridview(DataGridViewX gridView )
{
if (gridView.Rows.Count == 0)
return false;
//建立Excel对象
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;
//生成字段名称
for (int i = 0; i < gridView.ColumnCount; i++)
{
excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < gridView.RowCount - 1; i++)
{
for (int j = 0; j < gridView.ColumnCount; j++)
{
if (gridView[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + gridView[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
}
}
}
return true;
}
调用函数导出Excel
private void command1_Executed(object sender, EventArgs e)
{
//第一种到处方法,引用"Microsoft Office 11.0 Object Library" COM组件 ,
//可能你系统中存在的COM组件会是"Microsoft Office 9.0 Object Library"
//这种到处方法就是遍历一次dataGridView的数据,将其填充到Excel 里
this.ExportDataGridview(dataGridViewX1);
}
private void command1_Executed(object sender, EventArgs e)
{
//第一种到处方法,引用"Microsoft Office 11.0 Object Library" COM组件 ,
//可能你系统中存在的COM组件会是"Microsoft Office 9.0 Object Library"
//这种到处方法就是遍历一次dataGridView的数据,将其填充到Excel 里
this.ExportDataGridview(dataGridViewX1);
}
这种方法没有什么特殊,dataGridView有多少数据就导出多少数据,没有特殊的格式处理,所以速度较快。。
第二种稍微复杂但是却可以带来更多喜人的选择。
先引用 ReportViewer 需要的两个组件
Microsoft.ReportViewer.Common.dll和Microsoft.ReportViewer.WinForms.dll
通常通过在工具箱中拖放ReportViewer 控件即可自动引用两个组件。。
第一步先查询数据:
初始化数据
private ReportViewer reportViewer1 = new ReportViewer();
private DataTable dt = new DataTable();
public FrmMian()
{
InitializeComponent();
}
private void FrmMian_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=.;uid=sa;pwd=;DataBase=pubs;");
SqlDataAdapter dap = new SqlDataAdapter("select * from authors", con);
dap.Fill(dt);
dataGridViewX1.DataSource = dt.DefaultView;
this.reportViewer2.RefreshReport();
}
private ReportViewer reportViewer1 = new ReportViewer();
private DataTable dt = new DataTable();
public FrmMian()
{
InitializeComponent();
}
private void FrmMian_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=.;uid=sa;pwd=;DataBase=pubs;");
SqlDataAdapter dap = new SqlDataAdapter("select * from authors", con);
dap.Fill(dt);
dataGridViewX1.DataSource = dt.DefaultView;
this.reportViewer2.RefreshReport();
}
第二步 添加新项-数据集:设计一个dataTable,该表于查询的表结构一样
第三步:添加新项-报表 ,报表设计如下
通过工具栏拖放一个“表”控件到报表中,再从数据源中拖放字段,
可以给报表加边框,颜色,格式,写表达式,甚至包括一些数学运算,集合运算==
查看表的属性获取数据源字符串,在代码中会使用到
完成表设计后,将rdlc文件复制到Debug 文件夹下,因为那才是程序运行的 根目录
第四步编写导出按钮事件代码:
第二种导出数据的方法
private void command2_Executed(object sender, EventArgs e)
{
//设置关联的报表文件
reportViewer1.LocalReport.ReportPath =
Application.StartupPath + "\\报表1.rdlc";
//设置报表数据源
reportViewer1.LocalReport.DataSources.Add(
new ReportDataSource("DataSet1_authors", dt));
//保存Excel
SaveExcel();
}
private void SaveExcel()
{
Microsoft.Reporting.WinForms.Warning[] Warnings;
string[] strStreamIds;
string strMimeType;
string strEncoding;
string strFileNameExtension;
try
{
byte[] bytes = this.reportViewer1.LocalReport.Render("Excel", null, out strMimeType,
out strEncoding, out strFileNameExtension,
out strStreamIds, out Warnings);
string strFilePath = "";
saveFileDialog1.Title = "导出Excel";
saveFileDialog1.FileName = "报表1.xls";
saveFileDialog1.Filter = "Excel 文件(*.xls)|*.xls|所有文件(*.*)|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
saveFileDialog1.CheckPathExists = true;
strFilePath = saveFileDialog1.FileName;
using (System.IO.FileStream fs = new FileStream(strFilePath, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
System.Diagnostics.Process.Start(strFilePath);
}
}
catch
{
MessageBoxEx.Show("导出Excel出错","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
private void command2_Executed(object sender, EventArgs e)
{
//设置关联的报表文件
reportViewer1.LocalReport.ReportPath =
Application.StartupPath + "\\报表1.rdlc";
//设置报表数据源
reportViewer1.LocalReport.DataSources.Add(
new ReportDataSource("DataSet1_authors", dt));
//保存Excel
SaveExcel();
}
private void SaveExcel()
{
Microsoft.Reporting.WinForms.Warning[] Warnings;
string[] strStreamIds;
string strMimeType;
string strEncoding;
string strFileNameExtension;
try
{
byte[] bytes = this.reportViewer1.LocalReport.Render("Excel", null, out strMimeType,
out strEncoding, out strFileNameExtension,
out strStreamIds, out Warnings);
string strFilePath = "";
saveFileDialog1.Title = "导出Excel";
saveFileDialog1.FileName = "报表1.xls";
saveFileDialog1.Filter = "Excel 文件(*.xls)|*.xls|所有文件(*.*)|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
saveFileDialog1.CheckPathExists = true;
strFilePath = saveFileDialog1.FileName;
using (System.IO.FileStream fs = new FileStream(strFilePath, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
System.Diagnostics.Process.Start(strFilePath);
}
}
catch
{
MessageBoxEx.Show("导出Excel出错","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
总体Demo简单界面如下
Demo下载