有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将结果保存到Excel文件或csv文件?

我使用以下代码提取一些数据并将其保存到CSV文件中。但现在的问题是,程序会将数据写入CSV文件,每当代码再次运行时,就会将其删除,旧结果将替换为新结果! 问题是,有没有办法保存结果并将新结果存储在新行中?如果是,那么怎么做

这是我的代码:

 private void writeReport() {
    BufferedWriter out = null;
   try {
        FileWriter fstream = new FileWriter("out.csv");
        out = new BufferedWriter(fstream);
        out.write("File Name;");
        out.write("Total Lines of Code;");
        out.write("Executable Lines;");
        out.write("Lines of Comments;");
        out.write("Trivial Lines;");
        out.write("Empty Lines;");
        out.write("Code Complexity;");
        out.write("Number of Files;"); //to be changed to numver of files 
        out.write("Average File Complexity;"); //to be changed to averag file complexity
        out.write("Comment Percentage;"); //total
        out.write("Total Lines of Test Code;");
        out.write("Total Comments in Tests;");
        out.write("Total Trivial Lines in Tests;");
        out.write("Total Empty Lines in Tests;");
        out.write("Total Number of Test Files;");
        out.write("Comment Presentage in Test;");

        out.write(System.getProperty("line.separator"));

      //  for (int i = 0; i < newFiles.getNrOfFiles(); i++) {
            out.write("test" + ";");
        //    out.write(newFiles.getParser(i).getSourceFile().getName()+ ";");
            out.write(String.valueOf(newFiles.sumLinesOfCode()) + ";");
            out.write(String.valueOf(newFiles.sumLinesOfStatements()) + ";");
            out.write(String.valueOf(newFiles.sumLinesOfComments()) + ";");
            out.write(String.valueOf(newFiles.sumTrivialLines()) + ";");
            out.write(String.valueOf(newFiles.sumEmptyLines()) + ";");
            out.write(String.valueOf(newFiles.sumComplexity())+ ";");
            out.write(String.valueOf(newFiles.getNrOfFiles()) + ";");
            out.write(String.valueOf(newFiles.sumAvgComplexity()) + ";");
            out.write(String.valueOf((100 * newFiles.sumLinesOfComments()) / newFiles.sumLinesOfCode() + "%") + ";");

            out.write(System.getProperty("line.separator"));

        //Close the output stream
        out.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
      //  return;
    }
}

共 (3) 个答案

  1. # 2 楼答案

    FileWriter类还有另一个构造函数,它采用一个布尔值来确定是否附加到现有文件

    FileWriter(File file, boolean append)
    
  2. # 3 楼答案

    看看这个图书馆

    下面是一些示例代码(摘自org.apache.poi.hssf.dev.hssf测试类): 短rownum

    // create a new file
    FileOutputStream out = new FileOutputStream("workbook.xls");
    // create a new workbook
    Workbook wb = new HSSFWorkbook();
    // create a new sheet
    Sheet s = wb.createSheet();
    // declare a row object reference
    Row r = null;
    // declare a cell object reference
    Cell c = null;
    // create 3 cell styles
    CellStyle cs = wb.createCellStyle();
    CellStyle cs2 = wb.createCellStyle();
    CellStyle cs3 = wb.createCellStyle();
    DataFormat df = wb.createDataFormat();
    // create 2 fonts objects
    Font f = wb.createFont();
    Font f2 = wb.createFont();
    
    //set font 1 to 12 point type
    f.setFontHeightInPoints((short) 12);
    //make it blue
    f.setColor( (short)0xc );
    // make it bold
    //arial is the default font
    f.setBoldweight(Font.BOLDWEIGHT_BOLD);
    
    //set font 2 to 10 point type
    f2.setFontHeightInPoints((short) 10);
    //make it red
    f2.setColor( (short)Font.COLOR_RED );
    //make it bold
    f2.setBoldweight(Font.BOLDWEIGHT_BOLD);
    
    f2.setStrikeout( true );
    
    //set cell stlye
    cs.setFont(f);
    //set the cell format 
    cs.setDataFormat(df.getFormat("#,##0.0"));
    
    //set a thin border
    cs2.setBorderBottom(cs2.BORDER_THIN);
    //fill w fg fill color
    cs2.setFillPattern((short) CellStyle.SOLID_FOREGROUND);
    //set the cell format to text see DataFormat for a full list
    cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
    
    // set the font
    cs2.setFont(f2);
    
    // set the sheet name in Unicode
    wb.setSheetName(0, "\u0422\u0435\u0441\u0442\u043E\u0432\u0430\u044F " + 
                       "\u0421\u0442\u0440\u0430\u043D\u0438\u0447\u043A\u0430" );
    // in case of plain ascii
    // wb.setSheetName(0, "HSSF Test");
    // create a sheet with 30 rows (0-29)
    int rownum;
    for (rownum = (short) 0; rownum < 30; rownum++)
    {
        // create a row
        r = s.createRow(rownum);
        // on every other row
        if ((rownum % 2) == 0)
        {
            // make the row height bigger  (in twips - 1/20 of a point)
            r.setHeight((short) 0x249);
        }
    
        //r.setRowNum(( short ) rownum);
        // create 10 cells (0-9) (the += 2 becomes apparent later
        for (short cellnum = (short) 0; cellnum < 10; cellnum += 2)
        {
            // create a numeric cell
            c = r.createCell(cellnum);
            // do some goofy math to demonstrate decimals
            c.setCellValue(rownum * 10000 + cellnum
                    + (((double) rownum / 1000)
                    + ((double) cellnum / 10000)));
    
            String cellValue;
    
            // create a string cell (see why += 2 in the
            c = r.createCell((short) (cellnum + 1));
    
            // on every other row
            if ((rownum % 2) == 0)
            {
                // set this cell to the first cell style we defined
                c.setCellStyle(cs);
                // set the cell's string value to "Test"
                c.setCellValue( "Test" );
            }
            else
            {
                c.setCellStyle(cs2);
                // set the cell's string value to "\u0422\u0435\u0441\u0442"
                c.setCellValue( "\u0422\u0435\u0441\u0442" );
            }
    
    
            // make this column a bit wider
            s.setColumnWidth((short) (cellnum + 1), (short) ((50 * 8) / ((double) 1 / 20)));
        }
    }
    
    //draw a thick black border on the row at the bottom using BLANKS
    // advance 2 rows
    rownum++;
    rownum++;
    
    r = s.createRow(rownum);
    
    // define the third style to be the default
    // except with a thick black border at the bottom
    cs3.setBorderBottom(cs3.BORDER_THICK);
    
    //create 50 cells
    for (short cellnum = (short) 0; cellnum < 50; cellnum++)
    {
        //create a blank type cell (no value)
        c = r.createCell(cellnum);
        // set it to the thick black border style
        c.setCellStyle(cs3);
    }
    
    //end draw thick black border
    
    
    // demonstrate adding/naming and deleting a sheet
    // create a sheet, set its title then delete it
    s = wb.createSheet();
    wb.setSheetName(1, "DeletedSheet");
    wb.removeSheetAt(1);
    //end deleted sheet
    
    // write the workbook to the output stream
    // close our file.  (don't blow out our file handles
    wb.write(out);
    out.close();
    

    读取或修改现有文件

    读取文件也同样简单。要读入文件,请创建一个org.apache.poi.poifs.Filesystem的新实例,将一个打开的InputStream传递给构造函数,例如XLS的FileInputStream。构造一个新的org.apache.poi.hssf.usermodel.HSSFWorkbook实例,将文件系统实例传递给构造函数。从那里,您可以通过评估器方法(workbook.getSheet(sheetNum)sheet.getRow(rownum), etc)访问所有高级模型对象

    修改读入的文件很简单。您可以通过assessor方法检索对象,通过父对象的remove方法(sheet.removeRow(hssfrow))将其删除,并像创建新xls一样创建对象。修改完单元格后,只需像上面那样调用workbook.write(outputstream)

    这方面的一个例子可以在^{}中看到