Excel具有強大的圖表顯示、分析功能,這點毋庸置疑,但是如果將常規(guī)MIS系統(tǒng)中的數(shù)據(jù)以報表的形式在Excel中顯示,卻并不那么容易。在VSTO中,我們可以借助RDLC報表組件來滿足這種需求。
示例代碼下載
本系列所有示例代碼均在 Visual Studio 2010 Ultimate RTM + Office 2010 Professional Plus Beta x64 下測試通過
注:本次數(shù)據(jù)庫使用的是 SQL Server 2008 R2 x64 RTM
1、在VS2010中,新建一個Excel 2010 Workbook項目:
2、添加引用:
Microsoft.ReportViewer.WinForms
3、創(chuàng)建一個RDLC報表,添加一個報表參數(shù)p_Country:
報表的目的很簡單,用的Northwind數(shù)據(jù)庫,根據(jù)傳遞的參數(shù),從Customers表中查詢數(shù)據(jù)。
4、創(chuàng)建一個存儲過程:
IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'sp_LinqTest') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
DROP PROCEDURE dbo.sp_LinqTest
END
GO
CREATE PROCEDURE dbo.sp_LinqTest
(
@Country VARCHAR(20)
)
AS
SELECT * FROM dbo.Customers WHERE Country = @Country
GO
5、在項目中添加一個Linq to SQL Class,將Customers表和sp_LinqTest存儲過程添加進來:
6、打開Sheet1的設計界面,添加一個ComboBox:
7、初始化數(shù)據(jù):
ReportViewer rptExcel = new ReportViewer();
private void fnDataIni()
{
this.rptExcel.LocalReport.ReportEmbeddedResource = "RDLCInExcel.LinqRpt.rdlc";
Excel.Range range = this.Range["B4", "J22"];
this.Controls.AddControl(this.rptExcel, range, "rptInExcel");
NorthwindDataContext ctx = new NorthwindDataContext();
var result = from c in ctx.Customers
select c.Country;
foreach (string list in result.Distinct<string>().ToList<string>())
{
this.comCountry.Items.Add(list);
}
}
8、構(gòu)造數(shù)據(jù)源,傳遞報表參數(shù):
private void fnBuildDataSource(string v_strCountry)
{
NorthwindDataContext ctx = new NorthwindDataContext();
var datasource = from c in ctx.sp_LinqTest(v_strCountry)
orderby c.CustomerID
select c;
ReportParameter rpCountry = new ReportParameter("p_Country", v_strCountry);
this.rptExcel.LocalReport.SetParameters(new ReportParameter[] { rpCountry });
this.rptExcel.LocalReport.DataSources.Add(new ReportDataSource("sp_LinqTestResult", datasource.ToList()));
this.rptExcel.RefreshReport();
}
9、關聯(lián)事件:
private void Sheet1_Startup(object sender, System.EventArgs e)
{
this.fnDataIni();
this.fnBuildDataSource(this.comCountry.Text);
}
private void Sheet1_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.comCountry.SelectedIndexChanged += new System.EventHandler(this.comCountry_SelectedIndexChanged);
this.Startup += new System.EventHandler(this.Sheet1_Startup);
this.Shutdown += new System.EventHandler(this.Sheet1_Shutdown);
}
#endregion
private void comCountry_SelectedIndexChanged(object sender, EventArgs e)
{
this.rptExcel.LocalReport.DataSources.Clear();
this.fnBuildDataSource(this.comCountry.Text);
}
10、最終運行效果:
11、生產(chǎn)的Excel位于Debug/Release下:
小結(jié):
本次我們在VSTO中做了一個簡單的報表,使用了Linq to SQL,當然,如果能用Excel的原生功能做報表效果更好,使用VSTO可以大大簡化實現(xiàn)相同功能的方法,使得我們可以用更熟悉的方法來完成一些需求。
本站僅提供存儲服務,所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。