初次研究,仅写了几个常用的
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using System.IO; using CrystalDecisions.Windows.Forms; namespace Util { public class CrystalReport { private ReportDocument report = null; private CrystalReportViewer crv = null; public CrystalReport(string rptFile) { report = new ReportDocument(); report.Load(rptFile); } /// <summary> /// 设置报表的连接数据源 /// </summary> /// <param name="serverName"></param> /// <param name="dataBase"></param> /// <param name="userId"></param> /// <param name="password"></param> public void SetDataSource(string serverName, string dataBase, string userId, string password) { ConnectionInfo connInfo = new ConnectionInfo(); connInfo.ServerName = serverName; connInfo.DatabaseName = dataBase; connInfo.UserID = userId; connInfo.Password = password; foreach (Table table in report.Database.Tables) { TableLogOnInfo info = table.LogOnInfo; info.ConnectionInfo = connInfo; table.ApplyLogOnInfo(info); } } /// <summary> /// 将报表导出为字节数组,以便于写成文件 /// </summary> /// <returns></returns> public byte[] ExportData() { byte[] data= null; using (Stream sm = report.ExportToStream(ExportFormatType.PortableDocFormat)) { int len = 1024, num = 0; data = new byte[sm.Length]; byte[] b = new byte[1024]; while ((len = sm.Read(b, 0, 1024)) != 0) { Array.Copy(b, 0, data, num, len); num += len; } sm.Close(); } return data; } /// <summary> /// 导出到文件 /// </summary> /// <param name="fileName"></param> /// <returns>true为导出成功,false为导出失败</returns> public bool ExportToFile(string fileName) { FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Create); byte[] data = ExportData(); if (data != null) { fs.Write(data, 0, data.Length); } fs.Close(); return true; } catch (Exception ex) { fs.Close(); throw ex; return false; } } /// <summary> /// 获取报表预览器,将其添加到窗体的控件组中即可显示 /// </summary> /// <returns></returns> public CrystalReportViewer GetViewer() { if (crv == null) { crv = new CrystalReportViewer(); } crv.ReportSource = report; return crv; } public void Dispose() { if (crv != null) { crv.Dispose(); } } } }