使用Apache poi

时间:2015-07-25 21:27:49

标签: java excel apache-poi

在名为“chart.xlsx”的excel文件中,我有以下数据 -

名字年龄血液

ad 14 a +

为42 o +

sd 21 o -

df 55 ab -

fg 44 a -

gh 87 b -

hj 26 b +

jk 24 ab +

kl 28 b -

我使用apache poi读取这些数据,我想在excel文件中绘制折线图/散点图。

package tkl;
import java.io.*;
import java.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.charts.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;


public class DemoTrendTest {


public static void main(String[] args) {
    // TODO Auto-generated method stub
    try{
    FileInputStream fis= new FileInputStream(new File("D:\\Chart.xlsx"));
    XSSFWorkbook wb= new XSSFWorkbook(fis);

    XSSFSheet s= wb.getSheet("a");
    Iterator <Row> rowIterator = s.iterator();
    while (rowIterator.hasNext())
    {
        Row row = rowIterator.next();
        //For each row, iterate through all the columns
        Iterator<Cell> cellIterator = row.cellIterator();

        while (cellIterator.hasNext())
        {
            Cell cell = cellIterator.next();
            if(cell.getCellType()== Cell.CELL_TYPE_NUMERIC)
            {
                System.out.print(cell.getNumericCellValue() + "\t");
            }

        }

    }

    Drawing drawing = s.createDrawingPatriarch();
    ClientAnchor anchor= drawing.createAnchor(0, 0, 0, 0, 5, 4, 14, 20);
    Chart chart = drawing.createChart(anchor);
    ChartLegend legend = chart.getOrCreateLegend();
    legend.setPosition(LegendPosition.BOTTOM);
    ScatterChartData data = chart.getChartDataFactory().createScatterChartData();
    ValueAxis bottomAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
    ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
    leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
    ChartDataSource<Number> xs = DataSources.fromNumericCellRange(s, new CellRangeAddress(0, 0, 0, 2));
    ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(s, new CellRangeAddress(1, 10, 1,1));

//actually should get =SERIES(a!$B$1,,a!$B$2:$B$10,1) but getting =SERIES(,a!$A$1:$J$1,a!$B$2:$B$11,1)

    data.addSerie(xs, ys2);
    chart.plot(data, bottomAxis, leftAxis);
    FileOutputStream fileOut = new FileOutputStream("D://1chart.xlsx");
    wb.write(fileOut);
    fileOut.close();

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

}

我想在图表中绘制14,42,21,55,44,87,26,24,28数据。我面临的问题是图表中只有前3个值。我得到= SERIES(,一个!$ A $ 1:$ J $ 1,一个!$ B $ 2:$ B $ 11,1)但我想= SERIES(一个!$ B $ 1,一个!$ B $ 2:$ B $ 10,1)。如何获得图表中的所有值?谁能帮我吗。

1 个答案:

答案 0 :(得分:0)

您只提供3个x轴值:

ChartDataSource xs = DataSources.fromNumericCellRange(s, new CellRangeAddress(0, 0, 0, 2));

如果您将该行更改为:

ChartDataSource xs = DataSources.fromNumericCellRange(s, new CellRangeAddress(1, 10, 0, 1));

然后您将看到所有数据点。