Reputation: 69
Does anyone know how to loop through files in a directory with the script below? I have tried it but I don't know how to assign a variable to the following line:
CSVReader reader = new CSVReader(new FileReader(file));
It has to be a string which pops syntax errors.
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import au.com.bytecode.opencsv.CSVReader;
class Test {
public static void main(String[] args) throws IOException {
Workbook wb = new HSSFWorkbook();
CreationHelper helper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
CSVReader reader = new CSVReader(new FileReader("data.csv"));
String[] line;
int r = 0;
while ((line = reader.readNext()) != null) {
Row row = sheet.createRow((short) r++);
for (int i = 0; i < line.length; i++)
row.createCell(i)
.setCellValue(helper.createRichTextString(line[i]));
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
}
}
Upvotes: 0
Views: 747
Reputation: 1573
Hi i don't know if i correctly understand your question. But i would recommend trying something like this: You can use the Path and Files classes to loop through a directory. Then you can use your code for editing the files
import java.io.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import au.com.bytecode.opencsv.CSVReader;
class Test {
public static void main(String[] args) throws IOException {
// here you enter the path to your directory.
// for example: Path workDir = Paths.get("c:\\workspace\\csv-files")
Path workDir = Paths.get("path/to/dir");
// the if checks whether the directory truly exists
if (!Files.notExists(workDir )) {
// this part stores all files withn the directory in a list
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(workDir )) {
for (Path path : directoryStream) {
Workbook wb = new HSSFWorkbook();
CreationHelper helper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// here you insert the name of the file (stored in the Path object) into your method
CSVReader reader = new CSVReader(new FileReader(path.toString()));
String[] line;
int r = 0;
while ((line = reader.readNext()) != null) {
Row row = sheet.createRow((short) r++);
for (int i = 0; i < line.length; i++)
row.createCell(i)
.setCellValue(helper.createRichTextString(line[i]));
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(path.getName().replaceAll("csv", "xls"));
wb.write(fileOut);
fileOut.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
} else {
System.out.println("directory " + workDir.toString() + " does not exist" )
}
}
}
Upvotes: 3