当前位置: 首页 > 知识库问答 >
问题:

使用POI-XSSF在java中嵌入文件

邢俊悟
2023-03-14

我需要使用Java Apache POI在excel中嵌入文件(.ppt(x)、.doc(x)、.jpg、.txt、...)(格式为xlsx)。我找到了一个使用POI-HSSF在excel中嵌入文件(格式为xls)的示例

(使用Apache POI将文件嵌入到Excel中),

但此示例不适用于excel xlsx格式。有人知道使用poi-xssf是否可以做到这一点吗?

共有1个答案

柴飞扬
2023-03-14

“试试这个,对我有用……”使用这个jar来运行这段代码....1)POI-3.13-20150929.jar 2)POI-OOXML-3.13-20150929.jar 3)POI-OOXML-Schemas-3.13-20150929.jar

 public String getReport() throws RecordNotFoundException{ 
    ResultSet rs = null;
    ResultSet rs1 = null;
    Connection conn = null;
    CallableStatement cstm = null;
    PreparedStatement pstmt = null;
    try {
        HttpServletRequest request;
        HttpSession session;
        request = (HttpServletRequest) ActionContext.getContext().get(
                "com.opensymphony.xwork2.dispatcher.HttpServletRequest");
        session = request.getSession();
        conn = JndiConnection.getOracleConnection();
        String sReportName = "";
        ArrayList<String> mainData = new ArrayList<String>();
        conn = JndiConnection.getOracleConnection();
        cstm = conn.prepareCall("your procedure name");
        cstm.setString(1, first parameter);
        cstm.setString(2, second parameter);
        cstm.registerOutParameter(3, OracleTypes.CURSOR);
        cstm.execute();
        rs1 = (ResultSet) cstm.getObject(3);
        ResultSetMetaData rsmd = rs1.getMetaData();
        String sColumnData="Sr.No";
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                sColumnData+="~~" + rsmd.getColumnName(i);
        }
        String headerString=sColumnData.replace("Sr.No~~", "");
        mainData.add(headerString);
        while (rs1.next()) {
            System.out.println("data...............::" + rs1.getString(1));
            String sData = "data";
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String column=rs1.getString(rsmd.getColumnName(i));
                    if (column == null) {
                        String finalData = "";
                        sData += "~~" + finalData;
                    } else {
                        sData += "~~" + rs1.getString(rsmd.getColumnName(i));
                    }
            }
            String bodyData=sData.replace("data~~", "");
            mainData.add(bodyData);
            System.out.println();
        }
        System.out.println("main data...............::" + mainData);
        session.setAttribute("myReportData", mainData);
            sReportName = genReport(mainData, title in file, "file path");
            if (!"".equals(sReportName)) {
                session.setAttribute("myReportDataExcelFile", sReportName);
            }

        setFileInputStream(new BufferedInputStream(new FileInputStream(sReportName)));
        setFileName(new File(sReportName).getName());

    } catch (SQLException se) {

        throw new RecordNotFoundException(se);
    } catch (NestableException ne) {
        throw new RecordNotFoundException(ne);
    } catch (Exception e) {
        throw new RecordNotFoundException(e);
    } finally {
        try {
            JndiConnection.freeConnections(cstm, conn, rs, rs1);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return SUCCESS;
}"

上面的方法将从数据库中获取并放入列表中,现在使用bellow方法编写带有POI HSSF的xls文件。

        private String genReport(ArrayList<String> arrDisplayDataList, String FileName, String sTitleName, String sPath)
        throws Exception {
    String fileNameWithPath;
    Exception exception;
    int col = 0;
    int sno = 1;
    fileNameWithPath = "";
    String sFromate = "";
    Connection con = null;
    String ColumnDataList[] = null;
    System.out.println("::::: Inside genReport() 2:::::");
    try {
        String[] arrColumnList = arrDisplayDataList.get(0).split("~~");
        System.out.println("Length:::" + arrColumnList.length);
        if (arrColumnList.length > 1) {
            System.out.println("==Inside Of Record Data===");
            DateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss");
            Calendar cal = Calendar.getInstance();
            sFromate = dateFormat.format(cal.getTime());
            FileName = (new StringBuilder()).append(FileName).append("_").append(sFromate).toString();
            fileNameWithPath = (new StringBuilder()).append(sPath).append("/").append(FileName).append(".xls")
                    .toString();
            File f1 = new File((new StringBuilder()).append(sPath).append("/").append(FileName).append(".xls")
                    .toString());

            f1.getParentFile().mkdirs();

            HSSFWorkbook wb = new HSSFWorkbook();

            FileOutputStream fileOut = new FileOutputStream(f1);
            HSSFSheet sheets = wb.createSheet("Sheet" + (sno++));

            int row = 1;
            HSSFRow rows;
            if (row == 1) {
                rows = sheets.createRow(0);

                HSSFCell cells = rows.createCell(0);
                cells.setCellType(1);
                HSSFCellStyle cellStyle1 = wb.createCellStyle();
                cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                cellStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);
                cellStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);
                cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                cells.setCellStyle(cellStyle1);
                cells.setCellValue(sTitleName);

                HSSFCellStyle cellStyle = wb.createCellStyle();
                HSSFFont fontStyle = wb.createFont();
                cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                fontStyle.setColor(IndexedColors.BLACK.getIndex());
                fontStyle.setBoldweight((short) 700);
                fontStyle.setFontHeightInPoints((short) 12);
                cellStyle.setFillPattern((short) 1);
                cellStyle.setFont(fontStyle);
                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);

                cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
                cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
                cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);

                cells.setCellStyle(cellStyle);

                sheets.addMergedRegion(new CellRangeAddress(0, 0, 0, arrColumnList.length - 1));
                for (int columnIndex = 0; columnIndex < 50; columnIndex++) {
                    sheets.autoSizeColumn(columnIndex);
                }

            }
            rows = sheets.createRow(row++);
            for (col = 0; col < arrColumnList.length; col++) {
                HSSFCell cells = rows.createCell(col);
                String sVal = (String) arrColumnList[col];
                cells.setCellType(1);
                cells.setCellValue(sVal);
                HSSFCellStyle cellStyle = wb.createCellStyle();
                HSSFFont fontStyle = wb.createFont();
                fontStyle.setColor(IndexedColors.BLACK.getIndex());
                fontStyle.setBoldweight((short) 700);
                fontStyle.setFontHeightInPoints((short) 10);
                cellStyle.setFont(fontStyle);
                cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
                cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
                cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                cells.setCellStyle(cellStyle);
                for (int columnIndex = 0; columnIndex < 100; columnIndex++) {
                    sheets.autoSizeColumn(columnIndex);
                }

            }

            int rownum = 2;
            int rowcount = 0;
            for (int i = 1; i < arrDisplayDataList.size(); i++) {
                if (rownum >= 65000) {
                    sheets = wb.createSheet("Sheet " + (sno++));
                    rownum = 0;
                }
                rows = sheets.createRow(rownum++);
                String sData = ((String) arrDisplayDataList.get(i)).toString();
                String sSplitData[] = sData.split("~~");

                int xcount = 0;
                for (col = 0; col < sSplitData.length; col++) {

                    HSSFCell cells = rows.createCell(xcount++);

                    String sVal = sSplitData[col];

                    if (sVal.equalsIgnoreCase("Total")) {

                        HSSFCellStyle cellStyle = wb.createCellStyle();
                        HSSFFont fontStyle = wb.createFont();
                        fontStyle.setColor(IndexedColors.BLACK.getIndex());
                        fontStyle.setBoldweight((short) 600);
                        fontStyle.setFontHeightInPoints((short) 12);

                        cellStyle.setFont(fontStyle);

                        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
                        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
                        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
                        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
                        // cells.setCellStyle(cellStyle);
                        cells.setCellType(1);
                        for (int k = 3; k < rows.getLastCellNum(); k++) {// For
                                                                            // each
                                                                            // cell
                                                                            // in
                                                                            // the
                                                                            // row
                            rows.getCell(k).setCellStyle(cellStyle);// Set
                                                                    // the
                                                                    // sty;e
                        }
                        cells.setCellValue(sVal);
                        System.out.println("TTT:" + sVal);

                    } else {
                        /*
                         * HSSFCellStyle cellStyle = wb.createCellStyle();
                         * cellStyle
                         * .setBorderBottom(HSSFCellStyle.BORDER_THIN);
                         * cellStyle
                         * .setBorderTop(HSSFCellStyle.BORDER_THIN);
                         * cellStyle
                         * .setBorderRight(HSSFCellStyle.BORDER_THIN);
                         * cellStyle
                         * .setBorderLeft(HSSFCellStyle.BORDER_THIN);
                         * //cells.setCellStyle(cellStyle);
                         * cells.setCellType(1);
                         */
                        cells.setCellValue(sVal);

                    }

                }

            }

            wb.write(fileOut);
            fileOut.close();
        } else {
            fileNameWithPath = "NO RECORD FOUND";
        }
    } catch (Exception e) {
        System.out.println("Exception ::::" + e);
        e.printStackTrace();
        throw e;
    }
    return fileNameWithPath;
}
 类似资料:
  • 对于如何使用Apache POI将文件嵌入Excel的问题,我已经找到了kiwiwings的答案,但不幸的是,他的答案只涵盖了HSSF电子表格(XLS格式),而我们目前使用的是新的XSSF格式(XLSX),针对HSSF电子表格提出的解决方案将不起作用。我尝试移植它,但棺材上的最后一颗钉子来自这样一个事实,即在XSSF世界中没有等效的HSSFObjectData。 这就是我到目前为止所做的--我找到

  • 问题内容: 我已经找到了如何使用ApachePOI将文件嵌入Excel的问题的奇妙答案,但是不幸的是,他的答案仅涉及HSSF电子表格(XLS格式),我们目前正在使用新的XSSF格式(XLSX),以及解决方案为HSSF电子表格提出的建议将不起作用。我尝试移植它,但是棺材中的最后一个钉子来自XSSF世界中没有等效的HSSFObjectData。 到目前为止,这是我所做的-我找到了一种将文件附加到Exc

  • 我试图使用Java和Apache POI将简单的VLookup公式放入我的“.xlsx”文件中。 该公式有外部引用,但对我不起作用。 因此,为了给您提供更多细节,我使用了poi和POI-OOXML3.13版以及Excel2007。 我以这种方式将公式放入单元格(其中单元格是单元格): 2 3 问题是,它写入Excel文件,然后在计算时抛出错误: 它从来没有给我作为,它总是返回。它应该返回字符串值。

  • 我正在使用Apache POI将数据导出到Excel文件中。在一个奇怪的需求中,我需要使用这个POI在Excel中嵌入一个文件。我有这个文件,可以将其作为流或字节数组。在谷歌搜索了很多时间后,我怀疑POI是否真的支持我的需求。我们能把文件嵌入Excel吗?-( 干杯,阿诺普

  • 我正在使用ApachePOI,我创建了一个XSSF工作簿,并尝试打开一个xlsx文件。它在当地的一个地方很有效。但是,当我用Excel打开真正服务器(AWS EC2、Tomcat8、JDK 1.8)上的Excel文件时,它显示文件已损坏(.xls工作)。这是我的代码: 本地Spring4, jdk1.8, tomcat 8.0, maven 真正的AWS EC2亚马逊linux2,jdk1。8、t

  • HSSF是POI项目的Excel'97(-2007)文件格式的纯Java实现。XSSF是POI项目对Excel2007OOXML(.xlsx)文件格式的纯Java实现。 使用HSSF时是否有出口限制?