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
Related
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?
If suppose excel having date value format in any column means, I need to change the whole column as date format and insert "N/A" value in an empty record of the date column. Anyone, please help me to solve this.
private void processExcelFromLocal() {
FileInputStream fis = null;
try {
fis = new FileInputStream(
new File("/home/rajat/Downloads/excelFile.xlsx"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (fis != null) {
#SuppressWarnings("resource")
XSSFWorkbook workbook = null;
try {
workbook = new XSSFWorkbook(fis);
} catch (IOException e) {
e.printStackTrace();
}
XSSFSheet spreadsheet = workbook.getSheetAt(0);
for (int i = 0; i <= spreadsheet.getLastRowNum(); i++) {
XSSFRow row = spreadsheet.getRow(i);
String value = row.getCell().getStringCellValue();
}
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
enter image description here
this is the final output file. have to insert constant value in empty cells of date column without mentioning date column name. empty cells are highlighted as green colour.
Hello I am making a program to convert from .xls to .txt. My program works almost to perfection. It inserts into text well but the thing is it does not insert the xls file completely. It does not insert the last 20 rows. The xls I need to convert contains 1548 rows, of which 1528 are inserted correctly in the format I want. It seems weird to me that only 20 rows don't get inserted. Any ideas?
public class create_text_doc {
public void writing() {
try {
File textgen = new File("C:\\Users\\darroyo\\Desktop\\expru.txt");
FileOutputStream fos = new FileOutputStream(textgen);
OutputStreamWriter osw = new OutputStreamWriter(fos);
Writer w = new BufferedWriter(osw);
String FilePath = "C:\\Users\\darroyo\\Desktop\\saldos_to_conv.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);
Sheet hoja = wb.getSheet("Contratos");
int totalNoOfRows = hoja.getRows();
int totalNoOfCols = hoja.getColumns();
w.write("\n");
for (int row = 1; row < totalNoOfRows; row++) {
for (int col = 0; col < totalNoOfCols; col++) {
System.out.print(hoja.getCell(col,row).getContents() + "\t");
w.write("Deposito por Saldo Inicial|"+hoja.getCell(0,row).getContents()+"|EFECTIVO| | |0|0|0|0|0|0|0|"+hoja.getCell(1,row).getContents()+"|"+
new SimpleDateFormat("dd/MM/yyyy").format(Calendar.getInstance().getTime())+"|0|"+
new SimpleDateFormat("dd/MM/yyyy").format(Calendar.getInstance().getTime())+"|0|0|"+hoja.getCell(3,row).getContents()+"|"+
new SimpleDateFormat("dd/MM/yyyy").format(Calendar.getInstance().getTime())+"|0|0\n");
}
System.out.println();
}
} catch (IOException e) {
System.err.println("Problem writing txt file");
} catch (BiffException e) {
e.printStackTrace();
}
}
public static void main(String[]args) {
create_text_doc write = new create_text_doc();
write.writing();
}
}
The system.out.println in my for loop prints out all the rows correctly, the problem is when I put them in the text document. I thought it could be the problem but after removing it, I am still missing 20 rows.
I am using below code to copy couple of columns from one sheet to another in excel. But data is getting copied to new sheet but when i open that file and try to close it, it asks do you want to save it? What should i do.
FileInputStream fis;
try {
fis = new FileInputStream("C:\\Banks\\SBI.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet Sheet1 = wb.getSheet("new sheet");
XSSFSheet nfrntSheet = wb.createSheet("Original");
int n = Sheet1.getLastRowNum();
System.out.println(n);
for(int i = 0;i<n+11;i++)
{
XSSFRow r = nfrntSheet.createRow(i);
Cell c = r.createCell(0);
c.setCellFormula("'new sheet'!A"+(i-9));
nfrntSheet.autoSizeColumn(0);
}
for(int i = 0;i<n+11;i++)
{
XSSFRow r = nfrntSheet.getRow(i);
Cell c = r.createCell(1);
c.setCellFormula("'new sheet'!C"+(i-9));
nfrntSheet.autoSizeColumn(1);
}
for(int i = 0;i<=7;i++)
{
nfrntSheet.setColumnWidth(i, 5000);
}
nfrntSheet.setColumnWidth(1, 12000);
nfrntSheet.setColumnWidth(17, 30000);
fis.close();
FileOutputStream stream= new FileOutputStream(new File("C:\\Banks\\SBI.xlsx"));
wb.write(stream);
stream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CommandLineApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CommandLineApp.class.getName()).log(Level.SEVERE, null, ex);
}
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()