java依据数据源生成柱状图并放在excel中
时间: 2024-05-06 20:20:36 浏览: 147
要在Java中生成柱状图并将其放在Excel中,可以使用Apache POI和JFreeChart库。
步骤如下:
1.导入POI和JFreeChart库
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.data.category.*;
```
2.创建Excel工作簿和工作表
```java
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Bar Chart");
```
3.创建数据源并添加数据
```java
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.setValue(50, "", "Apples");
dataset.setValue(80, "", "Bananas");
dataset.setValue(120, "", "Oranges");
```
4.创建柱状图并设置样式
```java
JFreeChart barChart = ChartFactory.createBarChart(
"Fruit Sales", // 标题
"", // x轴标签
"Sales", // y轴标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向
false, // 是否显示图例
true, // 是否显示工具提示
false // 是否生成URL链接
);
CategoryPlot plot = barChart.getCategoryPlot();
plot.setRangeGridlinePaint(Color.BLACK); // 设置水平网格线颜色
```
5.将图表插入Excel中
```java
ByteArrayOutputStream chartOut = new ByteArrayOutputStream();
ChartUtilities.writeChartAsPNG(chartOut, barChart, 500, 300);
int chartIndex = workbook.addPicture(chartOut.toByteArray(), Workbook.PICTURE_TYPE_PNG);
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 8, 20);
drawing.createPicture(anchor, chartIndex);
```
完整代码示例:
```java
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.data.category.*;
public class BarChartExample {
public static void main(String[] args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Bar Chart");
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.setValue(50, "", "Apples");
dataset.setValue(80, "", "Bananas");
dataset.setValue(120, "", "Oranges");
JFreeChart barChart = ChartFactory.createBarChart(
"Fruit Sales",
"",
"Sales",
dataset,
PlotOrientation.VERTICAL,
false,
true,
false
);
CategoryPlot plot = barChart.getCategoryPlot();
plot.setRangeGridlinePaint(Color.BLACK);
ByteArrayOutputStream chartOut = new ByteArrayOutputStream();
ChartUtilities.writeChartAsPNG(chartOut, barChart, 500, 300);
int chartIndex = workbook.addPicture(chartOut.toByteArray(), Workbook.PICTURE_TYPE_PNG);
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 8, 20);
drawing.createPicture(anchor, chartIndex);
FileOutputStream fileOut = new FileOutputStream("BarChart.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
}
```
阅读全文