日期:2014-05-20 浏览次数:20766 次
class clsDyCrystalReportCore { /// <summary> /// 将传入的datatable转换成报表模板所需要的datatable /// 数据全部转换为string /// </summary> /// <param name="dt">来源表</param> /// <param name="tblName">各单表名称</param> /// <param name="fldsName">字段名称,以半角逗号分隔。</param> /// <returns>报表模板所需要的datatable</returns> public DataTable dtx(DataTable dt,String tblName,String fldsName) { String oneRow=""; DataSet1.BigTatableDataTable dtx1 = new DataSet1.BigTatableDataTable(); object[] obj = new object[dt.Columns.Count]; //特别注意:所选择的表的列的数目需<=Bigtable的字段数目 //请自行填写保护代码 //先列名称写到每个表的第一行 dtx1.Rows.Add(dtx1.NewRow()); //第一行的第一列写表的名称 dtx1.Rows[0][0] = tblName; //切割列名称字符串,写入第一行后面的位置 for (int i = 0; i < fldsName.Split(new char[] { ',' }).Length; i++) { dtx1.Rows[0][i+1] = fldsName.Split(new char[] {','})[i]; } //写入数据 for (int i = 0; i <dt.Rows.Count ; i++) { dtx1.Rows.Add(dtx1.NewRow()); //每一行的第一列,也就是f0,写入表名称。 dtx1.Rows[i+1][0] = tblName; //写数据 for (int j = 0; j < dt.Columns.Count ; j++) { oneRow = oneRow + "," + dt.Rows[i][j].ToString(); if (dt.Rows[i][j].ToString()=="" ) dtx1.Rows[i+1][j+1] = " "; else dtx1.Rows[i+1][j+1] = dt.Rows[i][j].ToString(); } } return dtx1; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; using System.Windows.Forms; using CrystalDecisions.Shared; using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using System.Data.OleDb; namespace DyCrystalReportDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { String connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Threading.Thread.GetDomain().BaseDirectory+ "bbtcrall.mdb" + ";"; //打开数据库连接 OleDbConnection cn = new OleDbConnection(connstr); DataTable dtxAll = new DataTable(); //容纳所有数据 OleDbDataAdapter da = new OleDbDataAdapter(); clsDyCrystalReportCore xCore = new clsDyCrystalReportCore(); //注意各表的字段数目不能大于我们设定的最大数目! //请自行添加错误保护和对象释放代码 //第1个表 DataTable dt1 = new DataTable(); DataTable dtx1 = new DataTable(); da = new OleDbDataAdapter("SELECT * From Test1_1", cn); da.Fill(dt1); dtx1 = xCore.dtx(dt1,"表1","编号,姓名,发信日期,其他"); dtxAll.Merge(dtx1); //第2个表,注意,这个表可以从不同的数据源获取! //重新初始化 dt1 = new DataTable(); dtx1 = new DataTable(); da = new OleDbDataAdapter("SELECT * From Test1_2", cn); da.Fill(dt1); dtx1 = xCore.dtx(dt1, "表2", "编号,姓名,入职日期,日期1,日期2"); dtxAll.Merge(dtx1); //第3个表,注意,这个表可以从不同的数据源获取! //重新初始化 dt1 = new DataTable(); dtx1 = new DataTable(); da = new OleDbDataAdapter("SELECT * From Test_4", cn); da.Fill(dt1); dtx1 = xCore.dtx(dt1, "表3", "年份,地区,指标,最大值,最小值"); dtxAll.Merge(dtx1); ReportDocument myReport = new ReportDocument(); string reportPath = System.Threading.Thread.GetDomain().BaseDirectory + "crystalreport1.rpt"; myReport.Load(reportPath); //绑定数据集 myReport.SetDataSource(dtxAll); crystalReportViewer1.ReportSource = myReport; crystalReportViewer1.RefreshReport(); } } }