本文将介绍如何使用Spire.XLS for Java在Excel中创建迷你图表,以及编辑和删除表格中的迷你图表。
创建迷你图表
import com.spire.xls.*;
import java.awt.*;
public class CreateSparklineChart {
public static void main(String[] args) {
//创建一个Workbook类对象并加载Excel文档
Workbook workbook = new Workbook();
workbook.loadFromFile( "test.xlsx");
//获取第一个工作表
Worksheet sheet = workbook.getWorksheets().get(0);
//添加折线迷你图,设置折折线迷你图格式
SparklineGroup sparklineGroup1 = sheet.getSparklineGroups().addGroup();
sparklineGroup1.setSparklineType(SparklineType.Line);
sparklineGroup1.setSparklineColor(new Color(153,50,204));
sparklineGroup1.setShowHighPoint(true);
//设置添加折现迷你图表的单元格以及图表生成的数据范围
SparklineCollection sparklines1 = sparklineGroup1.add();
sparklines1.add(sheet.getCellRange("B3:F3"), sheet.getCellRange("G3"));
//添加柱形迷你图,并设置图表颜色
SparklineGroup sparklineGroup2 = sheet.getSparklineGroups().addGroup();
sparklineGroup2.setSparklineType(SparklineType.Column);
sparklineGroup2.setSparklineColor(new Color(244,164,96));
sparklineGroup2.setShowHighPoint(true);
//设置添加柱形迷你图表的单元格以及图表生成的数据范围
SparklineCollection sparklines2 = sparklineGroup2.add();
sparklines2.add(sheet.getCellRange("B4:F4"), sheet.getCellRange("G4"));
//添加盈亏迷你图,并设置颜色
SparklineGroup sparklineGroup3 = sheet.getSparklineGroups().addGroup();
sparklineGroup3.setSparklineType(SparklineType.Stacked);
sparklineGroup3.setSparklineColor(new Color(255,20,147));
sparklineGroup3.setShowHighPoint(true);
//设置盈亏迷你图表的单元格以及图表生成的数据范围
SparklineCollection sparklines3 = sparklineGroup3.add();
sparklines3.add(sheet.getCellRange("B5:F5"), sheet.getCellRange("G5"));
//保存文档
workbook.saveToFile("AddSparkline.xlsx", ExcelVersion.Version2013);
workbook.dispose();
}
}
迷你图表创建效果:
编辑迷你图表
import com.spire.xls.*;
import com.spire.xls.core.spreadsheet.ISparklineGroup;
import com.spire.xls.core.spreadsheet.ISparklines;
public class ModifySparkline {
public static void main(String[] args) {
//创建实例,加载文档
Workbook wb = new Workbook();
wb.loadFromFile("AddSparkline.xlsx");
//获取工作表
Worksheet sheet = wb.getWorksheets().get(0);
//修改第2个迷你图组中迷你图表类型和数据范围
ISparklineGroup sparklineGroup = sheet.getSparklineGroups().get(1);
sparklineGroup.setSparklineType(SparklineType.Line);
ISparklines sparklines = sparklineGroup.get(1);
sparklines.refreshRanges(sheet.getCellRange("C4:F4"), sheet.getCellRange("G4"));
//保存文档
wb.saveToFile("ModifySparkline.xlsx", ExcelVersion.Version2013);
wb.dispose();
}
}
迷你图表修改结果:
删除迷你图表
import com.spire.xls.*;
import com.spire.xls.core.spreadsheet.ISparklineGroup;
public class ClearSparkline {
public static void main(String[] args) {
//创建实例,加载文档
Workbook wb = new Workbook();
wb.loadFromFile("AddSparkline.xlsx");
//获取工作表
Worksheet sheet = wb.getWorksheets().get(0);
//获取第三个迷你图表
ISparklineGroup sparklineGroup = sheet.getSparklineGroups().get(2);
//从工作表中删除图表
sheet.getSparklineGroups().clear((SparklineGroup) sparklineGroup);
wb.saveToFile("ClearSparkline.xlsx",ExcelVersion.Version2013);
wb.dispose();
}
}
迷你图表删除效果: