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.
Related
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'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?
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);
}
public class Excel {
public static void main(String[] args) throws IOException, FileNotFoundException {
try {
InputStream input = new BufferedInputStream(new FileInputStream("D:/one"));
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow next = (HSSFRow) rows.next();
System.out.println("\n");
Iterator cells = next.cellIterator();
while (cells.hasNext()) {
HSSFCell next2 = (HSSFCell) cells.next();
if (HSSFCell.CELL_TYPE_NUMERIC == next2.getCellType()) {
System.out.println(next2.getNumericCellValue() + "");
} else if (HSSFCell.CELL_TYPE_STRING == next2.getCellType()) {
System.out.println(next2.getStringCellValue());
} else if (HSSFCell.CELL_TYPE_BOOLEAN == next2.getCellType()) {
System.out.println(next2.getBooleanCellValue() + "");
} else if (HSSFCell.CELL_TYPE_BLANK == next2.getCellType()) {
System.out.println("BLANK ");
} else {
System.out.println("unknown cell type");
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
you have not given the file extension in your code for your file "D:/one" is it an xls ot xlsx or csv .
This line:
InputStream input = new BufferedInputStream(new FileInputStream("D:/one"));
...should be something like:
InputStream input = new BufferedInputStream(new FileInputStream("D:/folder/filename.xls"));
...depending on your file location and extension of course.
As an aside, I highly recommend JExcelAPI and this tutorial by Lars Vogel.