I'm trying to build code to import an Excel file, I've been following a video but in the end my code didn't work (I double-checked) I get this error
I believe, I have the right libraries and perhaps the video might be a little outdated and the code no longer functions.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel ImportDataFromExcelModel = (DefaultTableModel) jTable1.getModel();
FileInputStream excelFIS = null;
BufferedInputStream excelBIS = null;
XSSFWorkbook excelImportWorkBook = null;
String currentDirectoryPath = "";
JFileChooser excelFileChooserImport = new JFileChooser(currentDirectoryPath);
int excelChooser = excelFileChooserImport.showOpenDialog(null);
if (excelChooser == JFileChooser.APPROVE_OPTION) {
try {
File excelFile = excelFileChooserImport.getSelectedFile();
excelFIS = new FileInputStream(excelFile);
excelBIS = new BufferedInputStream(excelBIS);
excelImportWorkBook = new XSSFWorkbook(excelBIS);
XSSFSheet excelSheet = excelImportWorkBook.getSheetAt(0);
for(int num = 0 ; num < excelSheet.getLastRowNum() ; num++){
XSSFRow excelRow = excelSheet.getRow(num);
XSSFCell cell = excelRow.getCell(1);
System.out.println(cell);
ImportDataFromExcelModel.addRow(new Object [] {cell});
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
first half of the error message
second half of the error message
enter image description here
check your code at 14th row
I have such a code that generates using the POI library. The list contains 250,000 lines. The formation of an Excel file takes 30-40 minutes. Reading about POI, I realized that this is not normal. How to speed up the process?
private void create(List<User> list) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Statistic");
var rowCount = 0;
for (int i = 0; i < list.size(); i++) {
sheet.autoSizeColumn(i);
XSSFRow row = sheet.createRow(++rowCount);
XSSFCell loginCell = row.createCell(0);
loginCell.setCellValue(list.get(i).getLogin());
//...
XSSFCell amountSpecCell = row.createCell(9);
amountSpecCell.setCellValue(list.get(i).getLevel());
}
try {
FileOutputStream fileOutputStream = new FileOutputStream("myfilenew.xlsx");
workbook.write(fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
workbook.close();
}
}
I'm using Netbeans 8.2 and i create jar by clicking on clean and build icon, runnable jar works except when i want data to export to excel.
This is logic for exporting to excel:
public static void exportToExcel(TableView<T> tableView, Stage stage) {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet = hssfWorkbook.createSheet("Sheet1");
HSSFRow firstRow = hssfSheet.createRow(0);
//Getting column width
ExcelPropertiesCustomization.getColumnWidth(hssfSheet);
// Getting title properties
CellStyle naslov = ExcelPropertiesCustomization.getTitleProperties(hssfWorkbook);
//set titles of columns
for (int i = 0; i < tableView.getColumns().size(); i++) {
firstRow.createCell(i).setCellValue(tableView.getColumns().get(i).getText());
firstRow.getCell(i).setCellStyle(naslov);
}
// set cells for rest of the table
for (int i = 0; i < tableView.getItems().size(); i++) {
HSSFRow hssfRow = hssfSheet.createRow(i + 1);
for (int col = 0; col < tableView.getColumns().size(); col++) {
Object celValue = tableView.getColumns().get(col).getCellObservableValue(i).getValue();
try {
if (celValue != null) {
hssfRow.createCell(col).setCellValue(Double.parseDouble(celValue.toString()));
}
} catch (NumberFormatException e) {
hssfRow.createCell(col).setCellValue(celValue.toString());
} catch (NullPointerException e) {
System.out.println(e);
}
}
}
//save excel file and close the workbook
try {
File file = new File("FXdatabase.xls");
FileOutputStream out = new FileOutputStream(file);
hssfWorkbook.write(out);
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XLS files (*.xls)", "*.xls");
fileChooser.getExtensionFilters().add(extFilter);
File dest = fileChooser.showSaveDialog(stage);
if (dest != null) {
try {
Files.copy(file.toPath(), dest.toPath());
} catch (IOException ex) {
System.err.println(ex);
}
}
out.close();
} catch (IOException e) {
System.out.prinln(e);
}
}
It's not my first time that i export to excel using apache poi, but i never encouter this problem(i also have new lap top, don't know if that has something to do with problem), i suspect it's IOException. What can i do?
I need to have the data from a csv file into excel in selenium.
Having csv file in format like:
PERIOD|EMPLID|EMPL_RCD|HOME HOST|NAME|FIRST_NAME|LAST_NAME|FTE|EMPL_STATUS
5/04/2018|78787|0|Home|mandon|steven|jabobs|1|A
6/04/2018|78789|0|Home|stacy|carvin|tans|1|A
11/04/2018|17892|0|Home|neel|harvis|bammer|1|A
Need to have this data in excel like shown in image:
EDIT My attempt at creating an Excel file
I am using the below code for generating the (.xls) file from csv file with pipe symbol delimiter as shown in the image
but is is giving java.lang.NullPointerException after reading first line.
public class DelimitedToXls {
#SuppressWarnings("deprecation")
public static void main(String args[]) throws IOException {
ArrayList<ArrayList<String>> allRowAndColData = null;
ArrayList<String> oneRowData = null;
String fName = "C:\\input.csv";
String currentLine;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i = 0;
allRowAndColData = new ArrayList<ArrayList<String>>();
while ((currentLine = myInput.readLine()) != null) {
oneRowData = new ArrayList<String>();
String oneRowArray[] = currentLine.split(";");
for (int j = 0; j < oneRowArray.length; j++) {
oneRowData.add(oneRowArray[j]);
}
allRowAndColData.add(oneRowData);
System.out.println();
i++;
}
try {
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet sheet = workBook.createSheet("sheet1");
for (int i = 0; i < allRowAndColData.size(); i++) {
ArrayList<?> ardata = (ArrayList<?>) allRowAndColData.get(i);
HSSFRow row = sheet.createRow((short) 0 + i);
for (int k = 0; k < ardata.size(); k++) {
System.out.print(ardata.get(k));
HSSFCell cell = row.createCell((short) k);
cell.setCellValue(ardata.get(k).toString());
}
System.out.println();
}
FileOutputStream fileOutputStream = new FileOutputStream("C:\\outputFile.xls");
workBook.write(fileOutputStream);
fileOutputStream.close();
} catch (Exception ex) {
}
}
}
You can directly open the file with excel. Open file->Select file type: text file.
Select the file, then 'delimited' option on next window. Next window select 'other' and type | as delimiter.
Of course, save it as xls.
That's all.
You have 3 main options:
Open it directly with Excel and setting the delimiter as | (pipe)
Rewrite it as a valid CSV (Comma-Separated Values) file (ie, replace the pipes by commas)
Write the content of the file into a proper Excel file.
Option 1 - Open it directly with Excel
See Fabrizio's answer.
Option 2 - Rewrite it as a valid CSV file
If you are sure you have no commas in your file
You just need to replace all occurrences of | by , to have a valid csv (Comma-Separated Values) file. Then you can open it with Excel.
String fileName = "/path/to/your/file/textFile.txt";
String csvFileName = "/path/to/your/file/csvFile.csv";
try (BufferedReader br = new BufferedReader(new FileReader(fileName));
Writer writer = new FileWriter(csvFileName)) {
String line;
while ((line = br.readLine()) != null) {
writer.append(line.replaceAll("[|]", ","));
writer.append("\n");
}
} catch(Exception e) {
e.printStackTrace();
}
This code changes the content of your file to
PERIOD,EMPLID,EMPL_RCD,HOME HOST,NAME,FIRST_NAME,LAST_NAME,FTE,EMPL_STATUS
5/04/2018,78787,0,Home,mandon,steven,jabobs,1,A
6/04/2018,78789,0,Home,stacy,carvin,tans,1,A
11/04/2018,17892,0,Home,neel,harvis,bammer,1,A
If you might have commas in your file
You need to read token by token, and surround tokens which contain a comma by double quotes. Then replace all pipes by commas. Example, this line
5/04/2018|78787|0|Home, Work|mandon|steven|jabobs|1|A
Would be transformed to
5/04/2018,78787,0,"Home, Work",mandon,steven,jabobs,1,A
You can do it this way:
String fileName = "/path/to/your/file/textFile.txt";
String csvFileName = "/path/to/your/file/csvFile.csv";
try (BufferedReader br = new BufferedReader(new FileReader(fileName));
Writer writer = new FileWriter(csvFileName)) {
String line;
while ((line = br.readLine()) != null) {
String csvLine = Arrays.stream(line.split("[|]")) // split on pipes
.map(token -> token.contains(",") ? "\""+token+"\"" : token) // surround with double quotes if there is a comma in the value
.collect(Collectors.joining(",", "", "\n")); // join with commas
writer.append(csvLine);
}
} catch(Exception e) {
e.printStackTrace();
}
Option 3 - Writing to an Excel file
You can also create a proper Excel file .xls or .xlsx using the Apache POI library. Here is an example using POI-OOXML 3.17 (latest version as of today) You can get it from Maven Repository
String fileName = "/path/to/your/file/textFile.txt";
String excelFileName = "/path/to/your/file/excelFile.xlsx";
// Create a Workbook and a sheet in it
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
// Read your input file and make cells into the workbook
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
Row row;
Cell cell;
int rowIndex = 0;
while ((line = br.readLine()) != null) {
row = sheet.createRow(rowIndex);
String[] tokens = line.split("[|]");
for(int iToken = 0; iToken < tokens.length; iToken++) {
cell = row.createCell(iToken);
cell.setCellValue(tokens[iToken]);
}
rowIndex++;
}
} catch(Exception e) {
e.printStackTrace();
}
// Write your xlsx file
try (FileOutputStream outputStream = new FileOutputStream(excelFileName)) {
workbook.write(outputStream);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
You can replace | with char \t and store that in .csv file.
I have done something similar while converting CSV to XLS:
try{
FileReader fr=new FileReader("TEJAS.CSV");
FileWriter fw=new FileWriter("TEJASEXEL.xls");
while((c=fr.read())!=-1){
if(c==','){
c='\t';
}
fw.write(c);
}
fr.close();
fw.close();
}
I'm trying to save the contents of a JTable to a file and then open the file when needed to bring up the original JTable. I am using the DefaultTableModel to add rows and columns to the JTable so I decided to save my model to a file. Here is my method:
public void outputfile(DefaultTableModel model) {
String filename = "data.file";
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(model);
oos.close();
}
catch(IOException e) {
System.out.println("There was a problem creating file: " + e);
return;
}
System.out.println("JTable correctly saved to file " + filename);
}
So now that my model is saved to data.file, I have a method that opens the file. Or...that's what it's supposed to do:
public void inputfile() {
String filename = "data.file";
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
model = (DefaultTableModel)ois.readObject();
}
catch(Exception e) {
System.out.println("Problem reading back table from file: " + filename);
return;
}
}
So, in my main I simply write:
outputfile(model); //to save model to file.
inputfile(); //to extract model from file and then apply it to the table.
table = new JTable(model);
So, thank you for reading but it's not working. Nothing happens when I use inputfile. help please?
public void writefile2(JTable table) {
try{
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
TableModel model = table.getTableModel();
for(int i = 0; i<model.getRowCount(); i++) {
for(int j = 0; j<model.getColumnCount(); j++) {
out.write((String)model.getValueAt(i, j));
}
}
out.close();
}catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
This code would dump JTable to a file
TableModel model = table.getModel();
for( int i = 0; i < model.getRowCount(); i++ )
{
for( int i = 0; i < model.getColumnCount(); j++ )
{
//Create your File Writer
fileWriter.write( model.getValueAt( i, j );
}
}
In reverse direction you can call setValueAt()