POI printing

Download the required jar package of poi. Here
I take printing the product information sheet as an example.
There are two printing methods:
one is to print with regular settings, and the other is to
print with a template that you have made yourself.

1. Import the jar package of poi in the project
write picture description here

In the maven project:
write picture description here

2. Eight steps for printing requirements:
1) Create a workbook
2) Create a worksheet
3) Create a row object row (the starting value of the subscript is 0)
4) Create a cell object cell (the starting value of the subscript is 0) The value is 0)
5) Set the content of the cell
6) Set the style of the cell, set the font and font size
7) Save, close the stream object
8) Download

3. Prepare in advance to set the style of the data and tables that need to be printed
write picture description here

4. Background code example:

/**
 * 打印出根据名称模糊查询到的商品信息
 */
@RequestMapping("/print/{goodName}")
public String print(@PathVariable String goodName,HttpServletResponse response,HttpServletRequest request) throws Exception {
    goodName = new String(goodName.getBytes("ISO-8859-1"),"UTF-8");  
    //通用变量
    int rowNo=0,cellNo=1;//行号   列号
    Row nRow =null;//行对象
    Cell nCell = null;//单元格对象

    //1.创建工作簿
    //Workbook wb = new HSSFWorkbook();//只支持excel2003版本        扩展名xls
    //Workbook wb = new XSSFWorkbook();  //支持excel2007+版本          扩展名xlsx
      Workbook wb = new SXSSFWorkbook();  //支持excel2007+版本          扩展名xlsx   不支持模板操作,可以将产生的一部分对象从内存中转移到磁盘。
                                          //默认转移对象的个数为100,如果new SXSSFWorkbook(500)代表内存中对象个数达到500就转移到磁盘
    //2.创建工作表
    Sheet sheet = wb.createSheet();

    //设置列宽   本身是个bug会出现一些偏差  
    sheet.setColumnWidth(cellNo++, 18*256);
    sheet.setColumnWidth(cellNo++, 14*256);
    sheet.setColumnWidth(cellNo++, 10*256);
    sheet.setColumnWidth(cellNo++, 10*256);
    sheet.setColumnWidth(cellNo++, 10*256);
    sheet.setColumnWidth(cellNo++, 8*256);
    sheet.setColumnWidth(cellNo++, 10*256);
    sheet.setColumnWidth(cellNo++, 10*256);

    cellNo=1;//重置

    //3.创建行对象
    //=========================================大标题=============================
    nRow = sheet.createRow(rowNo++);//创建行对象
    nRow.setHeightInPoints(36);//设置行高
    nCell = nRow.createCell(cellNo);//创建单元格对象

    //合并单元格
    sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));//横向合并单元格

    //设置单元格的内容
    nCell.setCellValue(goodName+"商品信息数据表");

    //设置单元格样式
    nCell.setCellStyle(this.bigTitle(wb));

    //=======================================小标题=================================
    String titles[] = {"名称","描述","价格","市场价格","发货地","已售","库存","上架时间"};

    //创建小标题的行对象
    nRow = sheet.createRow(rowNo++);
    nRow.setHeightInPoints(26.25f);//设置行高

    //创建单元格对象,并设置内容 ,并设置样式
    for(String title :titles){
        nCell = nRow.createCell(cellNo++);//创建单元格对象
        nCell.setCellValue(title);//设置内容
        nCell.setCellStyle(this.title(wb));//设置样式
    }

    //=======================================数据输出=================================================
    //查询到我想要打印的商品信息的集合
    List<Good> list = goodService.getByGoodName(goodName);

    for(Good good :list){
      nRow = sheet.createRow(rowNo++);//产生数据行
      nRow.setHeightInPoints(24);//设置行高

      cellNo=1;
      nCell = nRow.createCell(cellNo++);//产生单元格对象
      nCell.setCellValue(good.getName());//商品名称
      nCell.setCellStyle(this.text(wb));//设置文本样式

      nCell = nRow.createCell(cellNo++);//产生单元格对象
      nCell.setCellValue(good.getDescription());//商品描述
      nCell.setCellStyle(this.text(wb));//设置文本样式

      nCell = nRow.createCell(cellNo++);//产生单元格对象
      nCell.setCellValue(good.getPrice().toString());     //商品价格
      nCell.setCellStyle(this.text(wb));//设置文本样式


      nCell = nRow.createCell(cellNo++);//产生单元格对象
      nCell.setCellValue(good.getMarketprice().toString());//市场价格
      nCell.setCellStyle(this.text(wb));//设置文本样式


      nCell = nRow.createCell(cellNo++);//产生单元格对象
      nCell.setCellValue(good.getSource());//发货地
      nCell.setCellStyle(this.text(wb));//设置文本样式


      nCell = nRow.createCell(cellNo++);//产生单元格对象
      nCell.setCellValue(good.getSalenum());//已售
      nCell.setCellStyle(this.text(wb));//设置文本样式

      nCell = nRow.createCell(cellNo++);//产生单元格对象
      nCell.setCellValue(good.getStorage());//库存
      nCell.setCellStyle(this.text(wb));//设置文本样式

      nCell = nRow.createCell(cellNo++);//产生单元格对象
      nCell.setCellValue(UtilFuns.dateTimeFormat(good.getAddtime()));//上架时间
      nCell.setCellStyle(this.text(wb));//设置文本样式
   }

    //======================================输出到客户端(下载)========================================
    DownloadUtil downUtil = new DownloadUtil();

    ByteArrayOutputStream  baos = new ByteArrayOutputStream();//流  内存中的缓存区
    wb.write(baos);//将excel表格中的内容输出到缓存
    baos.close();//刷新缓存

    downUtil.download(baos, response,request, "商品信息表.xlsx");//如果是中文,下载时可能会产生乱码,如何解决?
    return null;
}

//大标题的样式
public CellStyle bigTitle(Workbook wb){
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setFontName("宋体");
    font.setFontHeightInPoints((short)16);
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);                   //字体加粗

    style.setFont(font);

    style.setAlignment(CellStyle.ALIGN_CENTER);                 //横向居中
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);      //纵向居中

    return style;
}
//小标题的样式
public CellStyle title(Workbook wb){
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setFontName("黑体");
    font.setFontHeightInPoints((short)12);

    style.setFont(font);

    style.setAlignment(CellStyle.ALIGN_CENTER);                 //横向居中
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);      //纵向居中

    style.setBorderTop(CellStyle.BORDER_THIN);                  //上细线
    style.setBorderBottom(CellStyle.BORDER_THIN);               //下细线
    style.setBorderLeft(CellStyle.BORDER_THIN);                 //左细线
    style.setBorderRight(CellStyle.BORDER_THIN);                //右细线

    return style;
}

//文字样式
public CellStyle text(Workbook wb){
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setFontName("Times New Roman");
    font.setFontHeightInPoints((short)10);

    style.setFont(font);

    style.setAlignment(CellStyle.ALIGN_LEFT);                   //横向居左
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);      //纵向居中

    style.setBorderTop(CellStyle.BORDER_THIN);                  //上细线
    style.setBorderBottom(CellStyle.BORDER_THIN);               //下细线
    style.setBorderLeft(CellStyle.BORDER_THIN);                 //左细线
    style.setBorderRight(CellStyle.BORDER_THIN);                //右细线

    return style;
}

5. Effect display:
Start the project, find the fashionable products in the product name (I have checked out a total of eight products here),
write picture description here
click on the print method to access my background, and the print is successful:
write picture description here

6. View the file:
write picture description here


1. Prepare the template first
write picture description here

2. Put the template file under the webapp
write picture description here

3. Write the background printing method:

/**
 * 打印出根据名称查询到的商品信息(模板打印)
 */
@RequestMapping("/print/{goodName}")
public String print(@PathVariable String goodName,HttpServletResponse response,HttpServletRequest request) throws Exception {
    goodName = new String(goodName.getBytes("ISO-8859-1"),"UTF-8");  
    //通用变量
    int rowNo=0,cellNo=1;
    Row nRow =null;
    Cell nCell = null;

    //1.读取工作簿(我放入webapp中的模板)
    String path = request.getSession().getServletContext().getRealPath("/")+"/make/print/good.xlsx";
    System.out.println(path);

    InputStream is = new FileInputStream(path);
    Workbook wb = new XSSFWorkbook(is);

    //2.读取工作表
    Sheet sheet = wb.getSheetAt(0);

    cellNo=1;//重置

    //3.创建行对象
    //=========================================大标题=============================
    nRow = sheet.getRow(rowNo++);//读取行对象
    nCell = nRow.getCell(cellNo);
    //设置单元格的内容
    nCell.setCellValue(goodName+"商品信息数据表");

    //=======================================小标题=================================
    rowNo++;

    //=======================================数据输出=================================================
    nRow = sheet.getRow(rowNo);//读取第三行
    CellStyle goodNameCellStyle = nRow.getCell(cellNo++).getCellStyle();
    CellStyle descriptionCellStyle = nRow.getCell(cellNo++).getCellStyle();
    CellStyle priceCellStyle = nRow.getCell(cellNo++).getCellStyle();
    CellStyle marketPriceCellStyle = nRow.getCell(cellNo++).getCellStyle();
    CellStyle sourceCellStyle = nRow.getCell(cellNo++).getCellStyle();
    CellStyle saleNumCellStyle = nRow.getCell(cellNo++).getCellStyle();
    CellStyle storageCellStyle = nRow.getCell(cellNo++).getCellStyle();
    CellStyle addTimeCellStyle = nRow.getCell(cellNo++).getCellStyle();

    List<Good> list = goodService.getByGoodName(goodName);

    for(Good good : list){
        nRow = sheet.createRow(rowNo++);//产生数据行
        nRow.setHeightInPoints(24);//设置行高

        cellNo=1;
        nCell = nRow.createCell(cellNo++);//产生单元格对象
        nCell.setCellValue(good.getName());//商品名称
        nCell.setCellStyle(goodNameCellStyle);//设置文本样式

        nCell = nRow.createCell(cellNo++);//产生单元格对象
        nCell.setCellValue(good.getDescription());//描述
        nCell.setCellStyle(descriptionCellStyle);//设置文本样式

        nCell = nRow.createCell(cellNo++);//产生单元格对象
        nCell.setCellValue(good.getPrice().toString());//价格
        nCell.setCellStyle(priceCellStyle);//设置文本样式

        nCell = nRow.createCell(cellNo++);//产生单元格对象
        nCell.setCellValue(good.getMarketprice().toString());//市场价格
        nCell.setCellStyle(marketPriceCellStyle);//设置文本样式

        nCell = nRow.createCell(cellNo++);//产生单元格对象
        nCell.setCellValue(good.getSource());//发货地
        nCell.setCellStyle(sourceCellStyle);//设置文本样式

        nCell = nRow.createCell(cellNo++);//产生单元格对象
        nCell.setCellValue(good.getSalenum());//已售
        nCell.setCellStyle(saleNumCellStyle);//设置文本样式

        nCell = nRow.createCell(cellNo++);//产生单元格对象
        nCell.setCellValue(good.getStorage());//库存
        nCell.setCellStyle(storageCellStyle);//设置文本样式

        nCell = nRow.createCell(cellNo++);//产生单元格对象
        nCell.setCellValue(UtilFuns.dateTimeFormat(good.getAddtime()));//上架时间
        nCell.setCellStyle(addTimeCellStyle);//设置文本样式
    }

    //======================================输出到客户端(下载)========================================
    DownloadUtil downUtil = new DownloadUtil();

    ByteArrayOutputStream  baos = new ByteArrayOutputStream();//流  内存中的缓存区
    wb.write(baos);//将excel表格中的内容输出到缓存
    baos.close();//刷新缓存

    downUtil.download(baos, response,request, "商品信息表.xls");//如果是中文,下载时可能会产生乱码,如何解决?

    return null;

}
//大标题的样式
public CellStyle bigTitle(Workbook wb){
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setFontName("宋体");
    font.setFontHeightInPoints((short)16);
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);                   //字体加粗

    style.setFont(font);

    style.setAlignment(CellStyle.ALIGN_CENTER);                 //横向居中
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);      //纵向居中

    return style;
}
//小标题的样式
public CellStyle title(Workbook wb){
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setFontName("黑体");
    font.setFontHeightInPoints((short)12);

    style.setFont(font);

    style.setAlignment(CellStyle.ALIGN_CENTER);                 //横向居中
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);      //纵向居中

    style.setBorderTop(CellStyle.BORDER_THIN);                  //上细线
    style.setBorderBottom(CellStyle.BORDER_THIN);               //下细线
    style.setBorderLeft(CellStyle.BORDER_THIN);                 //左细线
    style.setBorderRight(CellStyle.BORDER_THIN);                //右细线

    return style;
}

//文字样式
public CellStyle text(Workbook wb){
    CellStyle style = wb.createCellStyle();
    Font font = wb.createFont();
    font.setFontName("Times New Roman");
    font.setFontHeightInPoints((short)10);

    style.setFont(font);

    style.setAlignment(CellStyle.ALIGN_LEFT);                   //横向居左
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);      //纵向居中

    style.setBorderTop(CellStyle.BORDER_THIN);                  //上细线
    style.setBorderBottom(CellStyle.BORDER_THIN);               //下细线
    style.setBorderLeft(CellStyle.BORDER_THIN);                 //左细线
    style.setBorderRight(CellStyle.BORDER_THIN);                //右细线

    return style;
}

4. Effect display:
the same as above, inquire about the fashionable products in the product name to print
write picture description here

Open the file and view it successfully:
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324899461&siteId=291194637