天天看點

c#調用Excel繪制圖表

c#調用Excel需要引用命名空間

using Microsoft.Office.Interop.Excel;      

由于該程式不複雜,主要是根據不同資料畫表和圖,畫的圖像也并不複雜,因為畫圖和畫表的操作會重複使用,是以,我把畫表和圖的操作放在一個類中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
namespace Excel
{
    class SheetControl
    {
        Worksheet sheet;
        public SheetControl(Worksheet sheet)
        {
            this.sheet = sheet;
        }

        /// <summary>
        /// 根據條件繪制圖表
        /// </summary>
        /// <param name="rg">繪制圖表的區域</param>
        /// <param name="data">資料區域</param>
        /// <param name="type">圖表類型,XlChartType枚舉類型</param>
        /// <param name="xlrc">設定以行或者列為系列,XlRowCol枚舉類型</param>
        /// <param name="title">表格标題</param>
        /// <param name="CategoryTitle">表格分類坐标名稱,即橫坐标名稱</param>
        /// <param name="ValueTitle">表格資料坐标的名稱,即縱坐标名稱</param>
        public void CreateChart(Range rg, Range data, Object type = null, XlRowCol xlrc = XlRowCol.xlColumns, string title = null, string CategoryTitle = null, string ValueTitle = null)
        {
            ChartObjects charts = (ChartObjects)sheet.ChartObjects(Type.Missing);
            ChartObject chartObj = charts.Add(rg.Left, rg.Top, rg.Width, rg.Height);
            Chart chart = chartObj.Chart;
            chart.ChartWizard(data, type, Type.Missing, xlrc, 1, 1, true, title, CategoryTitle, ValueTitle, Type.Missing);
            chart.Legend.Position = XlLegendPosition.xlLegendPositionTop;
            
        }

        /// <summary>
        /// 根據參數建立表格
        /// </summary>
        /// <param name="title">表格第一個單元格内容</param>
        /// <param name="rows">行标題,每行的首個單元格内容</param>
        /// <param name="cols">列标題,沒列的首個單元格</param>
        /// <param name="data">表格資料</param>
        /// <param name="startRow">行開始位置</param>
        /// <param name="startCol">列開始位置</param>
        public void CreateTable(string title,string[] rows,string[] cols,string[,] data,int startRow,int startCol)
        {
            sheet.Cells[startRow, startCol] = title;
            for (int i = 0; i < cols.Length; i++)
            {
                sheet.Cells[startRow, i + startCol + 1] = cols[i];
            }
            for (int i = 0; i < rows.Length; i++)
            { 
                sheet.Cells[i+startRow+1,startCol]=rows[i];
                for (int j = 0; j < cols.Length; j++)
                {
                    sheet.Cells[i + startRow + 1, j + startCol + 1] = data[i, j];
                }
            }  
        }
        /// <summary>
        /// 設定表格的資訊,包括邊框,文字等
        /// </summary>
        public void SetType()
        {
            
            sheet.UsedRange.Font.Size = 12;
            sheet.UsedRange.Font.Name = "華文楷體";
            sheet.UsedRange.HorizontalAlignment = XlHAlign.xlHAlignCenter;//豎直居中
            sheet.UsedRange.VerticalAlignment = XlVAlign.xlVAlignCenter;//水準居中
            sheet.UsedRange.Borders.LineStyle = 1;//邊框
            sheet.UsedRange.Columns.AutoFit();//列寬自适應
            sheet.UsedRange.Rows.AutoFit();//行高自适應
            //設定邊框
            sheet.UsedRange.BorderAround(XlLineStyle.xlDouble, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());
        }
    }
}      

設定一個Excel全局變量

public Microsoft.Office.Interop.Excel.Application myexcel;      

設定資料并建立一個Excel畫表和圖

private void button1_Click(object sender, EventArgs e)
        {
            string[] rows = { "國家機關辦公建築","辦公建築","商場建築","飯店飯店建築","文化建築","醫療衛生建築","體育建築","綜合建築","教育建築","其他建築","總計"};
            string[] cols = { "本月","上月" };
            string[,] data ={{"3","5"},
                            {"0","66"},
                            {"1","36"},
                            {"2","27"},
                            {"0","7"},
                            {"2","2"},
                            {"0","2"},
                            {"0","29"},
                            {"0","2"},
                            {"0","2"},
                            {"8","178"}};

            DialogResult res = MessageBox.Show("是否生成 新的Excel ?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (res == DialogResult.Yes)
            {

                myexcel = new Microsoft.Office.Interop.Excel.Application();
                myexcel.Application.Workbooks.Add(Type.Missing);
                myexcel.Caption = "excel test";
                myexcel.Visible = true;
                Worksheet sheet = (Worksheet)myexcel.ActiveWorkbook.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                sheet.Name = "表2";
                SheetControl sc = new SheetControl(sheet);
                sc.CreateChart(sheet.get_Range("F2:O12"), sheet.get_Range((Range)sheet.Cells[2, 2], (Range)sheet.Cells[2 + rows.Length - 1, 2 + cols.Length]), XlChartType.xlColumnClustered, XlRowCol.xlColumns, "本月建築能耗監測情況", null, "月度機關面積電耗");
                //sheet.get_Range(sheet.Cells[2,2],sheet.Cells[2+rows.Length,2+cols.Length])
                sc.CreateTable("建築類型", rows, cols, data, 2, 2);
                sc.SetType();
            }
        }      

在建立一個Excel對象的時候是用

Microsoft.Office.Interop.Excel.Application myexcel = new Microsoft.Office.Interop.Excel.Application();      

也可以用ApplicationClass來建立

其中Application和ApplicationClass的聯系和差別

代碼中使用Application接口,實際在初始化執行個體時,系統使用Application Class類來初始化Application對象。

Worksheets.Add方法介紹:

Worksheets 對象的 Add 方法:建立工作表、圖表或宏表。建立的工作表将成為活動工作表。文法是:expression.Add(Before, After, Count, Type)

expression : 必需。該表達式傳回上面的對象之一。

Before : Variant 類型,可選。指定工作表對象,建立的工作表将置于此工作表之前。

After : Variant 類型,可選。指定工作表對象,建立的工作表将置于此工作表之後。

Count : Variant 類型,可選。要建立的工作表的數目。預設值為 1。

Type : Variant 類型,可選。指定工作表類型。