poi 5.2.2 使用Execl 数据创建word图表
时间: 2023-06-13 15:05:22 浏览: 61
在使用poi 5.2.2创建word图表时,需要先使用Excel创建好数据,然后通过poi读取Excel数据,最后将数据插入到word图表中。
下面是一个简单的示例代码:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFChartAxis;
import org.apache.poi.xwpf.usermodel.XWPFChartLegend;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class ExcelToWordChartExample {
public static void main(String[] args) throws Exception {
// 读取Excel文件
FileInputStream excelFile = new FileInputStream("data.xlsx");
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet sheet = workbook.getSheetAt(0);
// 创建Word文档
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Chart Example");
// 创建表格
XWPFTable table = document.createTable();
XWPFTableRow headerRow = table.getRow(0);
headerRow.getCell(0).setText("Month");
headerRow.addNewTableCell().setText("Sales");
// 填充表格数据
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
XWPFTableRow tableRow = table.createRow();
Cell monthCell = row.getCell(0);
Cell salesCell = row.getCell(1);
tableRow.getCell(0).setText(monthCell.getStringCellValue());
tableRow.getCell(1).setText(String.valueOf(salesCell.getNumericCellValue()));
}
// 创建图表
XWPFChart chart = document.createChart();
chart.setTitleText("Sales Chart");
chart.setTitleOverlay(false);
chart.createCategoryAxis().setLabel("Month");
XWPFChartAxis valueAxis = chart.createValueAxis();
valueAxis.setCrossAxis(chart.createCategoryAxis());
valueAxis.setCrosses("autoZero");
chart.getOrCreateLegend().setPosition(XWPFChartLegend.Position.BOTTOM);
// 设置图表数据源
chart.setDataSheet(sheet);
chart.plot(chart.getChartDataFactory().createLineChartData());
// 将文档保存到文件
FileOutputStream out = new FileOutputStream("chart_example.docx");
document.write(out);
out.close();
document.close();
workbook.close();
}
}
```
在这个示例代码中,我们首先使用`FileInputStream`读取Excel文件,然后使用`XWPFDocument`创建一个Word文档。接着,我们使用`XWPFTable`创建一个表格,并将Excel中的数据填充到这个表格中。最后,我们使用`XWPFChart`创建一个图表,并将Excel中的数据源设置为这个图表的数据源。
需要注意的是,在使用poi创建Word文档时,需要使用`XWPFDocument`类,而不是之前版本中的`HWPFDocument`。此外,需要使用`XWPFChart`类来创建图表。