【问题标题】:how to save results to Excel file or csv files?如何将结果保存到 Excel 文件或 csv 文件?
【发布时间】:2016-08-06 11:12:52
【问题描述】:

我正在使用以下代码提取一些数据并将它们保存到 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;
    }
}

【问题讨论】:

  • new FileWriter("out.csv", true); 怎么样?它将附加到当前文件。

标签: java database csv


【解决方案1】:

判断文件是否已经存在

File file = new File("out.csv");
boolean exists = file.exists();

如果文件存在则以追加模式打开写入器

FileWriter fstream = new FileWriter(file, exists /*=append*/);

仅在文件尚不存在时才写入标题。

if (!exists) {
    out.write("File Name;");
    ...
    out.write(System.getProperty("line.separator"));
}
// write new rows

当您使用PrintWriter 时,有些事情会变得更容易:

PrintWriter out;
...
PrintWriter out = new PrintWriter(new BufferedWriter(fstream));
...
out.println(); // easier than out.write(System.getProperty("line.separator"));

【讨论】:

  • 好主意,特别是带有布尔值的标题,但现在它每次运行时都会跳一行,所以标题是写的(这是完美的)但它每个转义(跳跃)一行它运行的时间。所以如果它在下一个运行时间写在第 2 行,它写在第 4 行,然后在第 6 行,我怎样才能让它写一行又一行?谢谢
  • @user5923402 当您在标题后写入换行符时,这也必须在 if (!exists) 的块内完成 - 请参阅我的编辑。
【解决方案2】:

FileWriter 类有另一个构造函数,它接受一个布尔值来确定是否追加到现有文件。

FileWriter(File file, boolean append)

【讨论】:

    【解决方案3】:

    查看这个库Apache POI

    这里是一些示例代码(摘自并改编自 org.apache.poi.hssf.dev.HSSF 测试类): 短行号;

    // 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 的新实例,将 Filesystem 实例传递给构造函数。从那里您可以通过他们的评估方法(workbook.getSheet(sheetNum)sheet.getRow(rownum), etc) 访问所有高级模型对象。

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

    这方面的一个例子可以在org.apache.poi.hssf.usermodel.examples.HSSFRead中看到

    【讨论】:

      【解决方案4】:

      您做得对(想法)只需创建带有 csv 扩展名的文件。 Check this out !

      【讨论】:

        【解决方案5】:

        我会简单地使用http://opencsv.sourceforge.net/

         CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
             // feed in your array (or convert your data to an array)
             String[] entries = "first#second#third".split("#");
             writer.writeNext(entries);
             writer.close();
        

        使用 Maven 或 Gradle 获取它:http://mvnrepository.com/artifact/com.opencsv/opencsv 或下载并手动将其包含在您的项目中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-09-30
          • 2019-06-19
          • 1970-01-01
          • 2019-03-25
          • 1970-01-01
          • 2014-05-29
          • 1970-01-01
          相关资源
          最近更新 更多