0

我有一个脚本,它读取 excel 表中的一行,用该行中每个单元格的内容填充数组列表,然后将其写入文本文件。我希望能够将其写入 pdf 文件(使用 iText),以便我也可以在文件中包含图像。问题是我不断收到错误消息,指出文档已关闭并且“无法添加元素”到文档中。以下是相关代码:

    public File processFile(File excelWorkbook) throws FileNotFoundException, IOException, DocumentException{

    System.out.println("Processing file...");
    FileInputStream fileInputStream = new FileInputStream(excelWorkbook);
    HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
    HSSFSheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> rowIterator = firstSheet.iterator();
    System.out.println("Please choose output file name.");
    String fName = this.chooseFileName();
    try{
    for(int cntr=1; cntr<=firstSheet.getPhysicalNumberOfRows(); cntr++){
        ArrayList<String> values = new ArrayList<String>();
        Row currentRow = firstSheet.getRow(cntr);

        for(int cntr2 = 0; cntr2<currentRow.getLastCellNum(); cntr2++){
            Cell currentCell = currentRow.getCell(cntr2, Row.RETURN_NULL_AND_BLANK);
            if(currentCell==null){
                //cell doesn't have anything in there
                values.add("-not in excel file-");
                continue;
            }else{
              switch(currentCell.getCellType()){
                case Cell.CELL_TYPE_STRING:
                    values.add(currentCell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_NUMERIC:

                    double num = currentCell.getNumericCellValue();
                    String numString = String.valueOf(num);
                    values.add(numString);
                    break;
              }
            }

        }
        //libF = writeArrayListToFile(values, fName);
        writePDF(values, fName);//the method that writes to pdf
    }

    }catch (NullPointerException e){
        System.out.println("Cell is null.");
        //e.printStackTrace();
    }
        fileInputStream.close();
        return libF;
}

这是 writePDF(ArrayList al, String fName) 方法:

    public void writePDF(ArrayList<String> al, String filepath) throws FileNotFoundException, DocumentException{
    PdfWriter.getInstance(document, new FileOutputStream(filepath));
    document.open();
    document.add(new Paragraph("Library"));
    for(String i: al){
        document.add(new Phrase(i+"\n"));
    }
    document.close();
}

为什么我不能连续写入这个文件?如果我写入一个文本文件,我可以很容易地关闭它并再次打开它,这样我就可以将所有信息从 excel 电子表格中获取到一个文本文件中。这似乎不适用于pdf文件。它无法轻松打开和关闭。有人可以告诉我应该如何修改我的代码吗?我想要的只是让脚本读取 excel 表中的行,将单元格内容添加到数组列表中,然后立即将数组列表添加到 pdf 文档中。它只需要对每一行都这样做。这适用于文本文件,但不适用于 pdf。

4

1 回答 1

1

您正在将每一写入 pdf 文档

您的 writePDF 函数有一个字段:

document

它没有在文件打开时初始化(相反我认为它是在构建时初始化的)在打开输出文件的同时初始化文档

于 2013-07-13T03:35:20.470 回答