绘制组合图表,记录一下,中间遇到的问题点, 1.获取行数
int rowNum = xSheet.UsedRange.CurrentRegion.Rows.Count;
int rowNum = xSheet.Range["A1".ToUpper()].CurrentRegion.Rows.Count;
2.重新绘制图表
Excel.Chart xChart = null;
if (xSheet.ChartObjects().Count > 0)
xChart = xSheet.ChartObjects("GroupChart").Chart;
else
xChart = xBook.Charts.Add();
xSheet.ChartObjects().Delete();
Excel.Chart xChart = xBook.Charts.Add();
3.清除单元格区域中的内容
xSheet.UsedRange.ClearContents();
完整的代码 引用Microsoft.Office.Interop.Excel,ExcelDna.Integration;
public static void OpenFOFSheets()
{
Excel.Application xApp = (Excel.Application)ExcelDnaUtil.Application;
Excel.Workbook xBook = xApp.ActiveWorkbook;
Excel.Worksheet xSheet = xBook.ActiveSheet;
int rowNum = xSheet.Range["A1".ToUpper()].CurrentRegion.Rows.Count;
xSheet.ChartObjects().Delete();
MoreCharts(xBook, xSheet, rowNum, fofName);
xBook.Save();
}
private static void MoreCharts(Excel.Workbook xBook, Excel.Worksheet xSheet, int rowNum, string fofName)
{
Excel.Chart xChart = xBook.Charts.Add();
string str = string.Format("A1:E{0}", rowNum);
Excel.Range range = xSheet.Range[str];
xChart.SetSourceData(range);
var chart1 = xChart.FullSeriesCollection(1);
chart1.ChartType = Excel.XlChartType.xlLine;
chart1.Format.Fill.ForeColor.RGB = Excel.XlRgbColor.rgbBlue;
var chart2 = xChart.FullSeriesCollection(2);
chart2.ChartType = Excel.XlChartType.xlLine;
chart2.Format.Fill.ForeColor.RGB = Excel.XlRgbColor.rgbDarkRed;
var chart3 = xChart.FullSeriesCollection(3);
chart3.ChartType = Excel.XlChartType.xlColumnClustered;
chart3.Format.Fill.ForeColor.RGB = Excel.XlRgbColor.rgbGray;
var chart4 = xChart.FullSeriesCollection(4);
chart4.ChartType = Excel.XlChartType.xlColumnClustered;
chart4.Format.Fill.ForeColor.RGB = Excel.XlRgbColor.rgbOrange;
chart3.AxisGroup = 2;
chart4.AxisGroup = 2;
double min = GetMinimumScale(xSheet, rowNum);
xChart.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlSecondary).MaximumScale = Math.Abs(min);
xChart.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlSecondary).MinimumScale = min;
xChart.Location(Excel.XlChartLocation.xlLocationAsObject, xSheet.Name);
xSheet.Shapes.Item("图表 1").Name = "GroupChart";
xSheet.Shapes.Item("GroupChart").Top = (float)(double)xSheet.get_Range("H6").Top;
xSheet.Shapes.Item("GroupChart").Left = (float)(double)xSheet.get_Range("H6").Left;
}
private static double GetMinimumScale(Excel.Worksheet xSheet, int rowNum)
{
string str = string.Format("D2:D{0}", rowNum);
Excel.Range range = xSheet.Range[str];
var arr = range.Value2;
List<double> arrDou = new List<double>();
for (int i = 0; i < range.Count; i++)
{
arrDou.Add(arr[i + 1, 1]);
}
double min = arrDou.Min();
min = Math.Floor(min * 100) / 100;
return min;
}
|