C# 操做 Excel Chart

  1. 添加sheet

    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
    xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
    //取得sheet1
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
    //添加sheet3,放在sheet1以後
    Microsoft.Office.Interop.Excel.Worksheet worksheet3 = workbook.Worksheets.Add(After: workbook.Worksheets[1]);
    添加sheet3
  2. 加入數據

    //首行表頭
    worksheet3.Cells[1, 1] = "數據A";
    worksheet3.Cells[1, 2] = "數據B";
    //A列單元格格式設置爲文本
    Excel.Range range = worksheet3.Range[worksheet3.Cells[1, 1], worksheet3.Cells[nolist.Count + 1, 1]];
    range.NumberFormat = "@";//"@"文本格式  "00"數字格式
    //加入數據
     for (int i = 0; i < 30; i++)
    {
        worksheet3.Cells[i + 2, 1] = i.ToString();
        worksheet3.Cells[i + 2, 2] = (i+100).ToString();
    }
    向sheet3加入數據
  3. 添加chart,type是柱狀:xl3DColumn

    //新增一個Chart,放在sheet1和sheet3之間
    workbook.Charts.Add(Missing.Value, Missing.Value, 1, Missing.Value);
    新增Chart,數據源是sheet3
  4. chart數據源

    Excel.Range chartRange = m_Sheet.get_Range("A1", "B32");
    數據源是sheet3的A1至B32數據
  5. chart初始化

    //數據源chartRange
    //chart顯示類型 Excel.XlChartType.xl3DColumn 3D柱狀圖
    //Excel.XlRowCol.xlColumns 指定特定數據列是行顯示仍是列顯示(xlColumns或xlRows)
    //false 是否包含圖例 此處選擇不包含
    workbook.ActiveChart.ChartWizard(chartRange, Excel.XlChartType.xl3DColumn, Type.Missing, Excel.XlRowCol.xlColumns, 1, 1, false, "chart1", "數據A", "數據B", "");
    用ChartWizard初始化Chart
  6. chart數據標籤

    //當前的統計圖只有一個組
    Excel.ChartGroup grp = (Excel.ChartGroup)workbook.ActiveChart.ChartGroups(1);
    Excel.Series s = (Excel.Series)grp.SeriesCollection(1);
    s.HasDataLabels = true;
    獲取當前Chart的圖,加入標籤
  7. chart前景色(柱體顏色)

    //當前Chart中的數據點(柱體)
    Excel.Points points = (Excel.Points)s.Points();
    //excel中的顏色枚舉,跟日常的RGB數值不一樣
    private enum excelcolor {
                紅色 = XlRgbColor.rgbRed,
                綠色 = XlRgbColor.rgbLimeGreen,
                藍色 = XlRgbColor.rgbDeepSkyBlue
    }
    //改變柱體顏色
    int pc = points.Count + 1;
    for (int i = 1; i < pc; i++)
    {
        Excel.Point point = points.Item(i);
        if (i < 10)
        {
            point.Format.Fill.ForeColor.RGB = (int)excelcolor.綠色;
        }
        else if (i < 20)
        {
            point.Format.Fill.ForeColor.RGB = (int)excelcolor.紅色;
        }
        else
        {
            point.Format.Fill.ForeColor.RGB = (int)excelcolor.藍色;
        }
    }
    改變Chart的前景色 
相關文章
相關標籤/搜索