在Winform中我常用的两种把DataGridView数据导出Excel的方法

 

ContractedBlock.gif ExpandedBlockStart.gif 第一种导出方法
ExpandedBlockStart.gifContractedBlock.gif /**//// <summary>
        
/// 将DataGridView控件中数据导出到Excel
        
/// </summary>
        
/// <param name="gridView">DataGridView对象</param>
        
/// <returns></returns>

        public bool ExportDataGridview(DataGridViewX gridView )
ExpandedBlockStart.gifContractedBlock.gif        
{
            
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++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                excel.Cells[
1, i + 1= gridView.Columns[i].HeaderText;
            }

            
//填充数据
            for (int i = 0; i < gridView.RowCount - 1; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
for (int j = 0; j < gridView.ColumnCount; j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
if (gridView[j, i].ValueType == typeof(string))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
{
                        excel.Cells[i 
+ 2, j + 1= "'" + gridView[j, i].Value.ToString();
                    }

                    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
{
                        excel.Cells[i 
+ 2, j + 1= gridView[j, i].Value.ToString();
                    }

                }

            }

            
return true;
        }

 

ContractedBlock.gif ExpandedBlockStart.gif 调用函数导出Excel
     private void command1_Executed(object sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
{
            
//第一种到处方法,引用"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 控件即可自动引用两个组件。。

第一步先查询数据:

 

 

ContractedBlock.gif ExpandedBlockStart.gif 初始化数据
    private ReportViewer reportViewer1 = new ReportViewer();
        
private DataTable dt = new DataTable();

        
public FrmMian()
ExpandedBlockStart.gifContractedBlock.gif        
{
            InitializeComponent();
        }


        
private void FrmMian_Load(object sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
{
            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 文件夹下,因为那才是程序运行的 根目录

第四步编写导出按钮事件代码:

 

ContractedBlock.gif ExpandedBlockStart.gif 第二种导出数据的方法
 private void command2_Executed(object sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
{
            
//设置关联的报表文件
            reportViewer1.LocalReport.ReportPath =
               Application.StartupPath 
+ "\\报表1.rdlc";
            
//设置报表数据源
            reportViewer1.LocalReport.DataSources.Add(
                
new ReportDataSource("DataSet1_authors", dt));

            
//保存Excel
            SaveExcel();
        }


        
private void SaveExcel()
ExpandedBlockStart.gifContractedBlock.gif        
{
            Microsoft.Reporting.WinForms.Warning[] Warnings;
            
string[] strStreamIds;
            
string strMimeType;
            
string strEncoding;
            
string strFileNameExtension;

            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
byte[] bytes = this.reportViewer1.LocalReport.Render("Excel"nullout 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)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    saveFileDialog1.CheckPathExists 
= true;
                    strFilePath 
= saveFileDialog1.FileName;

                    
using (System.IO.FileStream fs = new FileStream(strFilePath, FileMode.Create))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
{
                        fs.Write(bytes, 
0, bytes.Length);
                    }


                    System.Diagnostics.Process.Start(strFilePath);
                }

            }

            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                MessageBoxEx.Show(
"导出Excel出错","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }

        }

 

 

总体Demo简单界面如下

 

Demo下载

/Files/a7373773/DataGirdViewToExcel.rar

转载于:https://www.cnblogs.com/a7373773/archive/2009/11/01/1593929.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值