读取文本文件,然后使用Java

时间:2018-09-19 22:46:38

标签: java excel

我正在读取一个文本文件,然后对该文件执行一些验证,然后尝试将该文件放入excel文件中。但是我只能将最后一行添加到excel文档中,而不是每行添加。任何帮助表示赞赏。谢谢。 这是我到目前为止的内容:

LinkedList<String[]> llist = new LinkedList<>();

String[] data;

File temp = new File("file.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
for (int i = 0; i < llist.size(); i++) {
    if(i==0){
        bw.newLine();
    }
    else{
        data = llist.get(i);

    String empid1 = data[0];
    String fname = data[1];
    String ccode1 = data[2];

    if(data[2].equals("IND")) {
        replace = data[2].replaceAll("IND", "IN");
        ccode1 = replace;
    }
    else if(data[2].equals("USA")) {
        replace = data[2].replaceAll("USA", "US");
        ccode1 = replace;
    }

    else {
        ccode1 = data[2];
    }

    String newData=empid1+","+fname+","+ccode1;

    XSSFWorkbook workBook = new XSSFWorkbook();
    FileOutputStream outstream=new FileOutputStream("data.xls");
    XSSFSheet spreadSheet = workBook.createSheet("Clean");
    int row_num = 0;
    for(String[] str : llist) {
        XSSFRow row = spreadSheet.createRow(row_num++);
        int cell_num = 0;
        for(String value : str) {
            XSSFCell cell = row.createCell(cell_num++);
            cell.setCellValue(value);
        }
    }

    workBook.write(outstream);
}
}

bw.close();

}

}

1 个答案:

答案 0 :(得分:1)

像这样重写代码:

LinkedList < String[] > llist = new LinkedList < > ();

String[] data;

File temp = new File("file.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));

XSSFWorkbook workBook = new XSSFWorkbook();
FileOutputStream outstream = new FileOutputStream("data.xls");
XSSFSheet spreadSheet = workBook.createSheet("Clean");

for (int i = 0; i < llist.size(); i++) {
 if (i == 0) {
  bw.newLine();
 } else {
  data = llist.get(i);

  String empid1 = data[0];
  String fname = data[1];
  String ccode1 = data[2];

  if (data[2].equals("IND")) {
   replace = data[2].replaceAll("IND", "IN");
   ccode1 = replace;
  } else if (data[2].equals("USA")) {
   replace = data[2].replaceAll("USA", "US");
   ccode1 = replace;
  } else {
   ccode1 = data[2];
  }

  //String newData=empid1+","+fname+","+ccode1;

  XSSFRow row = spreadSheet.createRow(i);

  XSSFCell cell = row.createCell(0);
  cell.setCellValue(empid1);

  cell = row.createCell(1);
  cell.setCellValue(fname);

  cell = row.createCell(2);
  cell.setCellValue(ccode1);
 }
}

workBook.write(outstream);
bw.close();