本文将介绍如何使用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();
}
}
迷你图表删除效果: