添加新行后,Excel文件不会更改

 IP-COM东莞办事处_426 发布于 2023-02-07 17:53

我开始做一个新的过程,将excel文件中的行添加到另一个excel文件,换句话说:将行追加到现有的Excel工作表.

为此,我正在测试以下代码,基于我在Internet上找到的代码:

私人全球声明:

private HSSFRow row;
private HSSFCell cell;
private FileInputStream inFile;
private POIFSFileSystem poiFile;
private HSSFSheet excelSheet = null;
private HSSFWorkbook excelBook = null;
private FileOutputStream outFile = null;
private static String outputFileName;

我用main方法开始一切:

public static void main(String args[]){
    outputFileName = "C:\\test1.xls";
    List newContent = new ArrayList<>();
    newContent.add("Test Val1");
    newContent.add("Test Val2");
    newContent.add("Test Val3");
    testingClass test = new testingClass();
    test.overwriteExcel(outputFileName,newContent);
}

有了这个我创建了文件,并且我假装更新它:

public void overwriteExcel(String outputFileName, List newContent){
    try{
    if(new File(outputFileName).exists()){  //--If the file exists/is already created
            outFile = new FileOutputStream(new File(outputFileName),true);  /*With the "true" parameter, the change must been applied but, nothing happens...*/
            inFile = new FileInputStream(new File(outputFileName));
            poiFile = new POIFSFileSystem(inFile);
            excelBook = new HSSFWorkbook(poiFile);
            excelSheet = excelBook.getSheetAt(0);
        }else{ //--Create the file
            outFile = new FileOutputStream(new File(outputFileName));
            excelBook = new HSSFWorkbook();
            excelSheet = excelBook.createSheet("Sheet1");
        }
        int i = 0;
        for(Iterator iter = newContent.iterator(); iter.hasNext();){
            Object val = iter.next();
            if(val!=null){
                row = excelSheet.createRow(excelSheet.getLastRowNum()+1);
                cell = row.createCell(0);  //--Temporaly, I change this val manually
                cell.setCelval(newContent.get(i++));
            }
        }
        excelBook.write(outFile);
        outFile.flush();
        outFile.close();
    }catch(Exception ex){
        JOptionPane.showMessageDialog(null,"Error: "+ex.getMessage(),"Warning!",JOptionPane.ERROR_MESSAGE);
    }
}

当课程结束他的过程时,我看到了文件并且我可以感知到文件大小的变化,但是当我打开它时,一切都是一样的,在我关闭文件之后,这将返回到他之前的大小......

试图理解发生了什么,我在row.createCell(0)中将"0"更改为"1",我删除了文件并重复了一下,一切正常,但是当我再次将值更改为"0"后,更改尚未应用...我不知道是否有一些文件权限...

我认为代码有问题,这不是我第一次使用excel文件,但这是我第一次尝试修改它.

提前谢谢!

1 个回答
  • 我曾经遇到过同样的情况而且很奇怪,你不必在追加模式下打开你的输出流:

    简而言之; 更改

    outFile = new FileOutputStream(new File(outputFileName),true);
    

    outFile = new FileOutputStream(new File(outputFileName));
    

    原因是write方法倾向于将完整的工作簿写入输出流,并且以追加模式打开将意味着"附加"现有工作簿以及由此创建的新工作簿并且它不会发生(这似乎"失败"无一例外).

    相反,输出流应该在'new'模式下打开(没有布尔值为true),这样就有一个最新的和最好的工作簿作为一个整体写入流.

    希望它有意义!:)

    我对您的代码进行了一些更改,这些更改与我对下面POI版本的理解一致,这非常有效:

    private FileInputStream inFile;
    private POIFSFileSystem poiFile;
    private XSSFRow row;
    private XSSFCell cell;
    private XSSFSheet excelSheet = null;
    private XSSFWorkbook excelBook = null;
    
    private static String outputFileName;
    
    public void overwriteExcel(File file, List<String> newContent) {
        try {
            if (file.exists()) {
                inFile = new FileInputStream(file);
                // poiFile = new POIFSFileSystem(inFile);
                excelBook = new XSSFWorkbook(inFile);
                excelSheet = excelBook.getSheetAt(0);
                System.out.println("Here -> " + excelSheet.getLastRowNum());
            } else { // --Create the file
                excelBook = new XSSFWorkbook();
                excelSheet = excelBook.createSheet("Sheet1");
            }
            int i = 0;
            for (String val : newContent.toArray(new String[newContent.size()])) {
                if (val != null) {
                    System.out.println("Row " + excelSheet.getLastRowNum());
                    row = excelSheet.createRow(excelSheet.getLastRowNum() + 1);
                    cell = row.createCell(0);
                    cell.setCellValue(newContent.get(i++));
    
                }
            }
            FileOutputStream outFile = new FileOutputStream(file);
            excelBook.write(outFile);
            // outFile.flush();
            outFile.close();
        } catch (Exception ex) {
            /*
             * JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage(),
             * "Warning!", JOptionPane.ERROR_MESSAGE);
             */
            ex.printStackTrace();
        }
    }
    
    public static void main(String args[]) {
        outputFileName = "demo4.xlsx";
        List<String> newContent = new ArrayList<>();
        newContent.add("Test Val1");
        newContent.add("Test Val2");
        newContent.add("Test Val3");
        WriteExcel test = new WriteExcel();
        test.overwriteExcel(new File(outputFileName), newContent);
    }
    

    2023-02-07 17:55 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有