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. But I am able to add only the last row into the excel document and not every row. 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.