简体   繁体   English

读取文本文件,然后使用Java将其上传到excel

[英]Read in a text file and upload it to excel using Java

I am reading in a text file, and then performing some validations on the file after which I am trying to put that file into an excel file. 我正在读取一个文本文件,然后对该文件执行一些验证,然后尝试将该文件放入excel文件中。 But I am able to add only the last row into the excel document and not every row. 但是我只能将最后一行添加到excel文档中,而不是每行添加。 Any help is appreciated. 任何帮助表示赞赏。 Thank You. 谢谢。 Here is what I have so far: 这是我到目前为止的内容:

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();

}

}

Rewrite your code like this: 像这样重写代码:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM