poi在Word中生成各种图表(支持柱状、组合、环状图、折线图、等常用图)
poi版本
1.maven坐标
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
2.poi官网指出需要poi4.x.x版本抛弃了jdk1.7之前的版本,所以适应此版本需要将jdk升级,如果不想升级还有另一种办法就是,使用springBoot单独做一个服务为你的主项目提供一个接口,让主项目去调用生成word流让主项目去接收即可。
效果图
1.刷新之前
2.刷新之后
代码
public class PoiDemoWordTable {
public static void main(String[] args) throws Exception {
final String returnurl=“d://poi/test.docx”;
final String templateurl=“D://poi/onepage.docx”;
InputStream is = new FileInputStream(new File(templateurl));
XWPFDocument doc = new XWPFDocument(is);
replaceAll(doc);
//文件存在删除
try {
File file = new File(returnurl);
if (file.exists()) {
file.delete();
}
FileOutputStream fos = new FileOutputStream(returnurl);
doc.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description: 替换段落和表格中
*/
public static void replaceAll( XWPFDocument doc) throws InvalidFormatException, FileNotFoundException, IOException{
/**----------------------------处理段落------------------------------------**/
List<XWPFParagraph> paragraphList = doc.getParagraphs();
if (paragraphList != null && paragraphList.size() > 0) {
for (XWPFParagraph paragraph : paragraphList) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
if (text != null) {
if (text.contains("${table1}")) {
run.setText("",0);
XmlCursor cursor = paragraph.getCTP().newCursor();
XWPFTable tableOne = doc.insertNewTbl(cursor);// ---这个是关键
XWPFTableRow tableOneRowOne = tableOne.getRow(0);//行
setWordCellSelfStyle(tableOneRowOne.getCell(0),"微软雅黑","9",1,"left","top","#ffffff","#4472C4",1,"序号");
XWPFTableCell cell12 = tableOneRowOne.createCell();
setWordCellSelfStyle(cell12,"微软雅黑","9",1,"left","top","#ffffff","#4472C4",1,"公司名称(英文)");
XWPFTableCell cell13 = tableOneRowOne.createCell();
setWordCellSelfStyle(cell13,"微软雅黑","9",1,"left","top","#ffffff","#4472C4",1,"公司名称(中文)");
XWPFTableRow tableOneRowTwo = tableOne.createRow();//行
tableOneRowTwo.getCell(0).setText("第二行第一列");
setWordCellSelfStyle(tableOneRowTwo.getCell(0),"微软雅黑","9",0,"left","top","#000000","#B4C6E7",1,"一行一列");
tableOneRowTwo.getCell(1).setText("第二行第二列");
setWordCellSelfStyle(tableOneRowTwo.getCell(1),"微软雅黑","9",0,"left","top","#000000","#B4C6E7",1,"一行一列");
tableOneRowTwo.getCell(2).setText("第二行