使用C#和Excel進行報表開發-產生統計圖Chart

來源:互聯網
上載者:User

    原文地址:http://www.opent.cn/a/094/1235.shtml

    有的Web項目選用Excel作為報表方案,在伺服器端產生Excel檔案,然後傳送到用戶端,由用戶端進行列印。在國內的環境下,相對PDF方式,Excel的安裝率應該比pdf閱讀器的安裝率要高,同時,微軟也為C#操作Excel提供了完備的介面,雖然ZedGraph和其他的商業報表工具產生的統計圖也很好,但是人家微軟畢竟是大品牌,值得信賴。

    本文進一步示範如何從指定的資料從頭產生統

    首先當然要添加對Excel的引用,然後需要定義幾個要用到的Excel對象

Excel.Application ThisApplication = null;Excel.Workbooks m_objBooks = null;Excel._Workbook ThisWorkbook = null;Excel.Worksheet xlSheet = null;

在建立一個新的_WorkBook對象的時候,預設的會含有3個Sheet,所以為了顯示清晰,將多餘的Sheet都刪掉:

 

private void DeleteSheet(){        foreach (Excel.Worksheet ws in ThisWorkbook.Worksheets)                if (ws != ThisApplication.ActiveSheet)                {                        ws.Delete();                }        foreach (Excel.Chart cht in ThisWorkbook.Charts)                cht.Delete();                        }

 

再下來需要添加用來給Chart提供資料的Sheet:

 

private void AddDatasheet(){        xlSheet = (Excel.Worksheet)ThisWorkbook.                Worksheets.Add(Type.Missing, ThisWorkbook.ActiveSheet,                Type.Missing, Type.Missing);         xlSheet.Name = "資料";}

 

產生Chart用到的資料,因為是示範,所以這裡使用產生隨機數的方法來替代從資料庫中提取資料。

 

private void LoadData(){        Random ran = new Random();        for (int i = 1; i <= 12; i++)        {                xlSheet.Cells[i,  1] = i.ToString() + "月";                xlSheet.Cells[i, 2] = ran.Next(2000).ToString();                }}

 

好了,到此,準備工作全部已經就緒,下面要進行Chart的產生設定部分了:

產生一個統計圖對象:

Excel.Chart xlChart = (Excel.Chart)ThisWorkbook.Charts.                Add(Type.Missing, xlSheet, Type.Missing, Type.Missing);

設定資料來源:

 

Excel.Range cellRange = (Excel.Range)xlSheet.Cells[1, 1];

 

通過嚮導產生Chart:

xlChart.ChartWizard(cellRange.CurrentRegion,                Excel.XlChartType.xl3DColumn, Type.Missing,                Excel.XlRowCol.xlColumns,1, 0, true ,                "訪問量比較(dahuzizyd.cnblogs.com)", "月份", "訪問量",                "");

到此,Chart的產生就完成了,貌似比較簡單,下面我們對其作一些設定,好更漂亮些。
設定統計圖Sheet的名稱:
xlChart.Name = "統計";
 
現在的統計圖只有一個組,他們會顯示成一樣的顏色,我們來讓12個Bar都顯示不同的顏色:

Excel.ChartGroup grp = (Excel.ChartGroup)xlChart.ChartGroups(1);grp.GapWidth = 20;grp.VaryByCategories = true;

現在Chart的條目的顯示形狀是Box,我們讓它們變成圓柱形,並給它們顯示加上資料標籤:

Excel.Series s = (Excel.Series)grp.SeriesCollection(1);s.BarShape = XlBarShape.xlCylinder;s.HasDataLabels = true;

 

下面再來設定統計圖的標題和圖例的顯示:

 

xlChart.Legend.Position = XlLegendPosition.xlLegendPositionTop;xlChart.ChartTitle.Font.Size = 24;xlChart.ChartTitle.Shadow = true;xlChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;

 

最後設定兩個軸的屬性,Excel.XlAxisType.xlValue對應的是Y軸,Excel.XlAxisType.xlCategory對應的是X軸:

 

Excel.Axis valueAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue, XlAxisGroup.xlPrimary);valueAxis.AxisTitle.Orientation = -90; Excel.Axis categoryAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory, XlAxisGroup.xlPrimary);categoryAxis.AxisTitle.Font.Name = "MS UI Gothic"; 

 

到此,一切就緒了,下面要產生Chart,並將其存為一個Excel檔案:

private void button4_Click(object sender, EventArgs e){    try    {        ThisApplication = new Excel.Application();        m_objBooks = (Excel.Workbooks)ThisApplication.Workbooks;        ThisWorkbook = (Excel._Workbook)(m_objBooks.Add(Type.Missing));        ThisApplication.DisplayAlerts = false;        this.DeleteSheet();        this.AddDatasheet();        this.LoadData();        CreateChart();        ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing,                    Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,                Type.Missing, Type.Missing, Type.Missing, Type.Missing);    }    catch (Exception ex)    {        MessageBox.Show(ex.Message);    }    finally    {        ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);        ThisApplication.Workbooks.Close();        ThisApplication.Quit();                System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook);                System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication);        ThisWorkbook = null;        ThisApplication = null;        GC.Collect();        this.Close();    }}Excel.Application ThisApplication = null;Excel.Workbooks m_objBooks = null;Excel._Workbook ThisWorkbook = null;Excel.Worksheet xlSheet = null;/**//// /// 用產生的隨機數作資料/// private void LoadData(){    Random ran = new Random();    for (int i = 1; i <= 12; i++)    {        xlSheet.Cells[i,  1] = i.ToString() + "月";        xlSheet.Cells[i, 2] = ran.Next(2000).ToString();        }}/**//// /// 刪除多餘的Sheet/// private void DeleteSheet(){    foreach (Excel.Worksheet ws in ThisWorkbook.Worksheets)        if (ws != ThisApplication.ActiveSheet)        {            ws.Delete();        }    foreach (Excel.Chart cht in ThisWorkbook.Charts)        cht.Delete();            }/**//// /// 建立一個Sheet,用來存資料/// private void AddDatasheet(){    xlSheet = (Excel.Worksheet)ThisWorkbook.        Worksheets.Add(Type.Missing, ThisWorkbook.ActiveSheet,        Type.Missing, Type.Missing);    xlSheet.Name = "資料";}/**//// /// 建立統計圖         /// private void CreateChart(){    Excel.Chart xlChart = (Excel.Chart)ThisWorkbook.Charts.        Add(Type.Missing, xlSheet, Type.Missing, Type.Missing);    Excel.Range cellRange = (Excel.Range)xlSheet.Cells[1, 1];    xlChart.ChartWizard(cellRange.CurrentRegion,        Excel.XlChartType.xl3DColumn, Type.Missing,        Excel.XlRowCol.xlColumns,1, 0, true ,        "訪問量比較(dahuzizyd.cnblogs.com)", "月份", "訪問量",        "");    xlChart.Name = "統計";    Excel.ChartGroup grp = (Excel.ChartGroup)xlChart.ChartGroups(1);    grp.GapWidth = 20;    grp.VaryByCategories = true;    Excel.Series s = (Excel.Series)grp.SeriesCollection(1);    s.BarShape = XlBarShape.xlCylinder;    s.HasDataLabels = true;    xlChart.Legend.Position = XlLegendPosition.xlLegendPositionTop;    xlChart.ChartTitle.Font.Size = 24;    xlChart.ChartTitle.Shadow = true;    xlChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;                Excel.Axis valueAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue, XlAxisGroup.xlPrimary);    valueAxis.AxisTitle.Orientation = -90;    Excel.Axis categoryAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory, XlAxisGroup.xlPrimary);    categoryAxis.AxisTitle.Font.Name = "MS UI Gothic";}try{    ThisApplication = new Excel.Application();    m_objBooks = (Excel.Workbooks)ThisApplication.Workbooks;    ThisWorkbook = (Excel._Workbook)(m_objBooks.Add(Type.Missing));    ThisApplication.DisplayAlerts = false;    this.DeleteSheet();    this.AddDatasheet();    this.LoadData();    CreateChart();    ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing,                    Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,                Type.Missing, Type.Missing, Type.Missing, Type.Missing);}catch (Exception ex){    MessageBox.Show(ex.Message);}finally{    ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);    ThisApplication.Workbooks.Close();    ThisApplication.Quit();            System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook);                System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication);    ThisWorkbook = null;    ThisApplication = null;    GC.Collect();    this.Close();}

運行你的程式,開啟產生的Excel檔案,最終產生的Chart應該像這樣:

完成了Chart的產生,但是上面對於每個月只有一項資料,如果我想顯示多項呢,例如顯示每個月兩個頁面的範圍量的對比。方法很簡單,只要再多產生一組資料就可以了,我們修改下LoadData方法:

private void LoadData(){        Random ran = new Random();        for (int i = 1; i <= 12; i++)        {                xlSheet.Cells[i,  1] = i.ToString() + "月";                xlSheet.Cells[i, 2] = ran.Next(2000).ToString();xlSheet.Cells[i, 3] = ran.Next(1500).ToString();                }} 

再次運行程式,產生Chart看看,應該像下面的效果:

 

可以看到,兩組資料以不同的形狀顯示,同時,圖例部分也不再顯示1-12月共12項,而是顯示兩項,這是因為在上面的代碼中我們設定了ChartGroup的VaryByCategories 屬性:
grp.VaryByCategories = true;當我們有兩個以上的組時,這一項就失效了。
 
在用C#操作Excel的時候,恐怕最大的困難就在於不知道Excel提供的各個對象,以及它們的屬性,方法等資訊,好在MSDN裡有關於Excel的介面說明-Excel Primary Interop Assembly Reference,參照這些,相信很快就能上手了。


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.