import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import java.io.FileOutputStream;
import java.io.IOException;
public class WordWithLineChart {
public static void main(String[] args) throws IOException {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFChart chart = createLineChart(document);
XWPFRun run = paragraph.createRun();
String blipId = document.addPictureData(chart.getGraphicalChartData().getInputStream(), Document.PICTURE_TYPE_PNG);
int width = Units.toEMU(500);
int height = Units.toEMU(300);
run.addPicture(blipId, Document.PICTURE_TYPE_PNG, "Line Chart", width, height);
FileOutputStream out = new FileOutputStream("chart.docx");
document.write(out);
out.close();
System.out.println("Word document with line chart created successfully.");
}
private static XWPFChart createLineChart(XWPFDocument doc) {
XWPFChart chart = doc.createChart(10, 10, 500, 300);
XDDFDataSource<String> categoryDataSource = XDDFDataSourcesFactory.fromStringCellRange(doc.getTableArray(0), new CellRangeAddress(1, 4, 0, 0));
XDDFNumericalDataSource<Double> valueDataSource = XDDFDataSourcesFactory.fromNumericCellRange(doc.getTableArray(0), new CellRangeAddress(1, 4, 1, 1));
XDDFCategoryAxis categoryAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
XDDFValueAxis valueAxis = chart.createValueAxis(AxisPosition.LEFT);
valueAxis.setCrosses(AxisCrosses.AUTO_ZERO);
XDDFChartData data = chart.createData(ChartTypes.LINE, categoryAxis, valueAxis);
XDDFLineChartData lineData = (XDDFLineChartData) data;
XDDFLineChartData.Series series = (XDDFLineChartData.Series) lineData.addSeries(categoryDataSource, valueDataSource);
series.setTitle("Sample Data", null);
chart.plot(data);
return chart;
}
}