導出Excel是日常工作中常見的需求,而繪制餅圖和折線圖是其中的一種需求。在Java中,我們可以使用Apache POI和JFreeChart來實現這樣的需求。
首先是Apache POI,它是一個用于創建、讀取和操作Microsoft Office格式文件的Java庫。我們可以使用POI來創建新的Excel文件、讀取現有的Excel文件、修改現有的Excel文件等。以下是使用POI繪制餅圖和折線圖的示例代碼:
Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Report"); // 繪制餅圖 Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15); Chart chart = drawing.createChart(anchor); ChartLegend legend = chart.getOrCreateLegend(); PieChartData data = new PieChartDataBuilder().build(); ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); ChartSeries series = chart.addSeries(data); series.setTitle("Pie Chart"); // 繪制折線圖 Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 5, 0, 10, 15); Chart chart = drawing.createChart(anchor); ChartLegend legend = chart.getOrCreateLegend(); LineChartData data = new LineChartDataBuilder().build(); ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM); ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT); ChartSeries series = chart.addSeries(data); series.setTitle("Line Chart");
然后是JFreeChart,它是一個用于創建各種圖表的Java庫。除了繪制餅圖和折線圖,它還可以繪制柱狀圖、散點圖、面積圖等。以下是使用JFreeChart繪制餅圖和折線圖的示例代碼:
DefaultPieDataset data = new DefaultPieDataset(); data.setValue("Category 1", 23.0); data.setValue("Category 2", 56.5); data.setValue("Category 3", 34.5); JFreeChart chart = ChartFactory.createPieChart("Pie Chart", data, true, true, false); PiePlot plot = (PiePlot) chart.getPlot(); plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({1})")); FileOutputStream fos = new FileOutputStream("Pie Chart.xlsx"); ChartUtils.writeChartAsPNG(fos, chart, 600, 400); DefaultCategoryDataset data = new DefaultCategoryDataset(); data.addValue(1.0, "Series 1", "Category 1"); data.addValue(2.0, "Series 1", "Category 2"); data.addValue(3.0, "Series 1", "Category 3"); JFreeChart chart = ChartFactory.createLineChart("Line Chart", "Category", "Value", data, PlotOrientation.VERTICAL, true, true, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); FileOutputStream fos = new FileOutputStream("Line Chart.xlsx"); ChartUtils.writeChartAsPNG(fos, chart, 600, 400);
總之,無論使用Apache POI還是JFreeChart,我們均可以在Java中輕松實現導出Excel并繪制圖表的需求。