gpt4 book ai didi

java - 使用 Java 读入文本文件并将其上传到 Excel

转载 作者:行者123 更新时间:2023-12-02 10:47:52 24 4
gpt4 key购买 nike

我正在读取一个文本文件,然后对该文件执行一些验证,然后尝试将该文件放入 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();

}

}

最佳答案

像这样重写你的代码:

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

关于java - 使用 Java 读入文本文件并将其上传到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52415155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com