poi報表技術快速入門demo(帶圖片插入)

這裏寫圖片描述

maven依賴
 <!--POI-->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.9</version>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.9</version>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.9</version>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <version>3.9</version>
    </dependency>



下面是源代碼
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

/**
 * Created by admin on 2016/1/14.
 */
public class POITest {
    public static void main(String[] args) throws IOException {
        /*
        * 創建表格前  先自己建立一個excel的模板,方便以後直接拷貝對應的樣式  而不用自己設置單元格的樣式
        * */
        Workbook workbook = new XSSFWorkbook(new FileInputStream("G:/demo3.xlsx"));
        Sheet sheet1 = workbook.getSheet("Sheet1");
        CellStyle rowStyle = sheet1.getRow(1).getRowStyle();
        short height = sheet1.getRow(1).getHeight();
        CellStyle cellStyle = sheet1.getRow(1).getCell(0).getCellStyle();

/*set row style*/
        Row row2 = sheet1.createRow(2);
        row2.setHeight(height);

        row2.setRowStyle(rowStyle);

        Cell cell0 = row2.createCell(0);
        cell0.setCellValue("pawn");
        cell0.setCellStyle(cellStyle);

        Cell cell1 = row2.createCell(1);
        cell1.setCellValue(19);
        cell1.setCellStyle(cellStyle);


        cellStyle=sheet1.getRow(1).getCell(2).getCellStyle();


        Cell cell2 = row2.createCell(2);
        cell2.setCellValue("1993年9月11日");
        cell2.setCellStyle(cellStyle);





        Cell cell3 = row2.createCell(3);
/*
* 下面是插入圖片到指定的位置
* */
        InputStream inputStream = new FileInputStream("C:\\Users\\admin\\Desktop\\20160114155540.png");
        byte[] bytes = IOUtils.toByteArray(inputStream);
        int i = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
        Drawing drawing = sheet1.createDrawingPatriarch();
        CreationHelper creationHelper = workbook.getCreationHelper();
        ClientAnchor anchor = creationHelper.createClientAnchor();
//        定位圖片位置
        anchor.setRow1(2);
        anchor.setCol1(3);
        Picture picture = drawing.createPicture(anchor, i);
        picture.resize();

        OutputStream out = new FileOutputStream("G:/demo3.xlsx");
        workbook.write(out);
        out.close();
    }
}
發佈了77 篇原創文章 · 獲贊 8 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章