最近项目遇到一个需求,需要打印excel,然后将打印记录进行持久化,还要对excel中的参数进行计算。最开始的思路是,调用java自身的api—— javax.print包下面的打印功能,把excel转化为freemarker模板,网友们基本都是这样做的。但是,理想跟现实总是有差距的,这样做得到的结果是,调用的打印机始终都是与服务器连接的打印机,并且java支持的打印只能打印图片格式的,并不能打印文档,只好放弃。
然后换策略。另一种思路:前端页面上输入excel需要的内容,通过poi对excel进行读写,然后将excel转化成HTML页面返回给前端,前端页面调用打印机,这样任何一台电脑都可以打印啦~~
上代码:
1.前端页面:
![excel需要的输入的内容](https://img-blog.csdnimg.cn/20181206103256111.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW4xODQyODMyNTE5OQ==,size_16,color_FFFFFF,t_70)
2.更新excel
public void updateExcel(PrintVo printVo)throws Exception{
        String filePath = productPath;
        File excelFile = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(excelFile);
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        HSSFSheet sheet1 = workbook.getSheetAt(0);

        HSSFRow row5 = sheet1.getRow(5);
        row5.getCell(1).setCellValue(printVo.getGoodsName());

        HSSFRow row7 = sheet1.getRow(7);
        row7.getCell(1).setCellValue(printVo.getGoodsNum()+printVo.getUnits());

        HSSFRow row9 = sheet1.getRow(9);
        row9.getCell(1).setCellValue(printVo.getProDate());

        FileOutputStream os;
        os = new FileOutputStream(filePath);
        workbook.write(os);
        os.close();
    }

3.把excel转化成HTML

 public String excelToHtml() throws Exception {

        String filePath = productPath;
        File excelFile = new File(filePath);
        InputStream is = null;
        OutputStream out = null;
        StringWriter writer = null;
        String content = null;
        try {
            if (excelFile.exists()) {

                is = new FileInputStream(excelFile);
//                Workbook workBook = WorkbookFactory.create(is);
                HSSFWorkbook workBook = new HSSFWorkbook(is);
                ExcelToHtmlConverter converter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
                //设置不输出行号(1 2 3...)及列标(A B C...)等
                converter.setOutputColumnHeaders(false);
                converter.setOutputHiddenColumns(false);
                converter.setOutputColumnHeaders(false);
                converter.setOutputLeadingSpacesAsNonBreaking(false);
                converter.setOutputRowNumbers(false);
                converter.processWorkbook(workBook);

                writer = new StringWriter();
                Transformer serializer = TransformerFactory.newInstance().newTransformer();
                serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                serializer.setOutputProperty(OutputKeys.INDENT, "YES");
                serializer.setOutputProperty(OutputKeys.METHOD, "HTML");
                serializer.transform(
                        new DOMSource(converter.getDocument()),
                        new StreamResult(writer));
//                out = new FileOutputStream(htmlFile);
                content = writer.toString();
                //替换掉Sheet1 Sheet2 Sheet3...
                content = content.replaceAll("<h2>Sheet[\\d]</h2>", "")
                        .replaceAll("<h2>第[一二三四五六七八九十壹贰叁肆伍陆柒捌玖拾]页</h2>", "");

            }
        } catch (IOException | ParserConfigurationException | TransformerException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.close();
                }
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return content;
    }

4.前端打印返回的html页面

 if (res.resultCode == 0) {
                                    var printWin=window.open("打印窗口", "_blank");
                                    printWin.document.write(res.data);
                                    printWin.document.close();
                                    printWin.print();
                                    printWin.close();

5.效果图

JS调用打印机打印excel表格,poi对excel进行读写

相关文章: