您首先必須將Crystal Report設置爲使用ADO.NET架構。 (見下圖)。要生成模式,只需創建一個數據集並創建表來填充它。填充完成後,添加表格(將表格名稱添加到數據集中),然後可以將模式導出到xml文件。
List<Tuple<string, string>> sqlQueries = new List<Tuple<string, string>>();
// The sql queries below shoudl match the same column names
// you want to pull back from the database for yoru report
sqlQueries.Add(new Tuple<string, string>("Table1Name", "SELECT TOP 1 .... FROM ..."));
sqlQueries.Add(new Tuple<string, string>("SubReportName", "SELECT TOP 1 .... FROM ..."));
sqlQueries.Add(new Tuple<string, string>("SubReport2TableName", "SELECT TOP 1 .... FROM ..."));
SqlConnection connection = new SqlConnection(ConnectionString);
DataSet resultSet = new DataSet();
foreach (var tuple in sqlQueries)
{
SqlDataAdapter adapter = new SqlDataAdapter(tuple.Item1, connection);
DataTable schema = new DataTable();
adapter.Fill(schema);
schema.TableName = tuple.Item2;
resultSet.Tables.Add(schema);
}
// write out the schema to a file
string path = Path.Combine("PATH_TO_DATASET_XML.xml");
using (var writer = File.CreateText(path))
{
writer.Write(resultSet.GetXmlSchema().Replace(" encoding=\"utf-16\"", ""));
}
下使用,由於在水晶一個數據源報告
最後只是使用相同的XML文件來填補你的報表數據:
DataSet reportData = new DataSet();
SqlConnection connection = new SqlConnection();
SqlDataAdapter reportAdapter = new SqlDataAdapter();
reportAdapter.SelectCommand = new SqlCommand();
reportAdapter.SelectCommand.Connection = connection;
reportData.ReadXml("PATH_TO_DATASET_XML.xml");
List<Tuple<string, string>> sqlQueries = new List<Tuple<string, string>>();
sqlQueries.Add(new Tuple<string, string>("Table1Name", "SELECT .... FROM ..."));
sqlQueries.Add(new Tuple<string, string>("SubReportName", "SELECT .... FROM ..."));
sqlQueries.Add(new Tuple<string, string>("SubReport2TableName", "SELECT .... FROM ..."));
reportData.EnforceConstraints = false;
foreach (var tuple in sqlQueries)
{
reportAdapter.SelectCommand.CommandText = tuple.Item1;
try
{
reportAdapter.Fill(reportData, tuple.Item2.Trim());
}
catch (Exception ex)
{
// Handle your stuff
}
}
using (var exportReport = new ReportDocument())
{
exportReport.Load("PATH_TO_RPT_FILE.rpt");
exportReport.SetDataSource(reportData);
// export report to wherever you want
}
我建議而是在數據庫一側創建一個視圖(包含所有需要的數據)並打開該視圖的dt。 – 2013-06-18 10:44:40