Emp ID Name Salary
1.0 john 2000000.0
2.0 dean 4200000.0
3.0 sam 2800000.0
4.0 cass 600000.0
I have created this code:
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class sample2
{
public static void main(String[] args) {
new sample2().sample2();
}
}
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(test);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for reading the content from this excel file using POI library. My editor is Eclipse. But when i run the program I took this: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method sample2() is undefined for the type sample2
at sample2.main(sample2.java:17)
Any help?
Thank u in advance!
public class sample2
{
public static void main(String[] args) {
new sample2().sample2(); // This is wrong too.
}
}
All your code after this is pointless. Your class has basically ended with the second }.
You might want to move all that within your main() method.
Also, this piece of code in the main() method new sample2().sample2(); is wrong.
It should be like this
sample2 s = new sample2();
Delete the last curly brace in your code :
{
public static void main(String[] args) {
new sample2().sample2();
}
}
And then creat a method named test2() like this:
public void sample2(){ //Put your code here }
Related
Want to display the contents of csv/xlsx files in Object.I want to display each row of the file in an Object. Below is my code. I want to create a class named Item and store the name of the columns in it.
package com.pack;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.commons.io.FilenameUtils;
public class Final
{
public static void main(String[] args) throws IOException
{
final String extXlsx="xlsx";
final String extCSV="csv";
String ext = "C:\\Users\\swapnil.sanjay.saraf\\Desktop\\.xlsx";
List<Item> itemList = new ArrayList<>();
if(extXlsx.equals(FilenameUtils.getExtension(ext)))
{
String excelPath = "C:\\Users\\swapnil.sanjay.saraf\\Desktop\\ItemID.xlsx";
FileInputStream fileInputStream = new FileInputStream(new File(excelPath));
// Create Workbook instance holding .xls file
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
// Get the first worksheet
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows
Iterator<Row> rowIterator = sheet.iterator();
System.out.println("\n******XLSX FILE******\n");
while (rowIterator.hasNext())
{
Item item;
// Get Each Row
Row row = rowIterator.next();
// Iterating through Each column of Each Row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
// Checking the cell format
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
}
}
System.out.println("");
itemList.add(item);
}
}
else if(extCSV.equals(FilenameUtils.getExtension(ext)))
{
Scanner scanner = new Scanner(new File("C:\\Users\\swapnil.sanjay.saraf\\Desktop\\KitsCP.csv"));
scanner.useDelimiter(",");
System.out.println("\n******CSV FILE******\n");
while(scanner.hasNext()){
System.out.print(scanner.next()+" ");
}
scanner.close();
}
else{
System.out.println("Inavlid Extension");
}
}
}
I want to read xls file using JXl where xls file name is always changing, how to read that please help.
i tried below code
FileInputStream filepath = new FileInputStream("C:\\Users\\sameer.joshi\\Downloads\\*.xls");
FileInputStream filepath = new FileInputStream("C:\\Users\\sameer.joshi\\Downloads\\");
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
File directory = new File("C:\\Users\\sameer.joshi\\Downloads\\");
File[] all_XLS_Files = directory.listFiles(); //all files in that directory
for (File file : all_XLS_Files) { // iterate through all files in that directory
if(file.getName().endsWith(".xls")){ // select only xls files
//do something with your xls files here
//for example print out the file name
System.out.println(file.getName());
//or read one or all of them
FileInputStream fileInputStream = new FileInputStream(new File(file.getPath()));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
fileInputStream.close();
FileOutputStream out =
new FileOutputStream(new File(file.getPath()));
workbook.write(out);
out.close();
}
}
}
}
Try to add all fileNames inside a list and read all data of Excel file.
List<String>ArrayList xlsFiles=new ArrayList<String>();
xlsFiles.add("your all files Names");
for (String str:xlsFiles) {
readExcellData(str);
}
public List<String> readExcellData(String fileNameToProcess) throws IOException {
List<String> dataList = new ArrayList<String>();
List<Integer> rowNo=new ArrayList<Integer>();
List<Integer> colNo=new ArrayList<Integer>();
int countRow=1;
int countCol=1;
try {
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
rowNo.add(countRow);
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING: {
dataList.add(cell.getStringCellValue());
System.out.println(cell.getStringCellValue());
}
break;
}
}
}
return dataList;
} catch (FileNotFoundException ee) {
ee.printStackTrace();
} catch (IOException ee) {
ee.printStackTrace();
}
return dataList;
}
I think the issue is not how to read a xls file, but how to deal with the changing file names. if that is the case try to use a FilenameFilter to get your .xls files. Example :
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
File directory = new File("C:\\Users\\sameer.joshi\\Downloads\\");
//get all files which ends with ".xls"
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xls");
}
};
// all xls files are listed in this File[] array
File[] files = directory.listFiles(textFilter);
// iterate through your array and do something
for (File file : files) {
//read your .xls files here
System.out.println(file.getCanonicalPath());
}
}
}
How to create table in MySQL with the contents of first row in excel in java dynamically without hard-coding and creating and I have a excel in which columns are added or deleted frequently... so I need to update my table frequently with new columns.. anyone please help. I am using spring-jdbc to connect to database and creating maven project... and how to read a cell value with date in it with format MM/DD/YYYY? for reading excel data I am using Apache-poi..
I want table in mysql like
ID Employee Manager Onsite 4/15/2015 4/16/2015 4/17/2015
How do I create? Please refer the below excel..the major thing is after two day again another date column will be added to my excel..that also I need to save in table previously that I have created..I am not getting idea how it can be done... I can't create the table as I have created in my code...
My excel is like this.. and having more than 100 rows
ID Employee Manager Onsite 4/15/2015 4/16/2015 4/17/2015
1 raju ram offshore 8 8 8
My code
package controller;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import javax.sql.DataSource;
import model.PMOEmployee;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.jdbc.core.JdbcTemplate;
public class ExcelDBJDBCDAO implements ExcelDBDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public DataSource getDataSource() {
return dataSource;
}
public void setdataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public JdbcTemplate getjdbcTemplate() {
return jdbcTemplate;
}
public void setjdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void importdata() {
TODO Auto-generated method stub
table creation
String sql="create table PMO(Id int ,Employee varchar(50),Manager varchar(50),Onsite varchar(50))";
getjdbcTemplate().update(sql);
System.out.println("table created Successfully :)");
ArrayList<PMOEmployee> list = new ArrayList<PMOEmployee>();
try
{
FileInputStream file = new FileInputStream(new File("/home/svenkatakishore/Untitled 1.xls"));
//Create Workbook instance holding reference to .xlsx file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first/desired sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
PMOEmployee employee = new PMOEmployee();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
if (cell.getColumnIndex() == 0) {
employee.setId((int)cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING:
if (cell.getColumnIndex() == 1) {
employee.setEmployeeName(cell.getStringCellValue());
}
else if (cell.getColumnIndex() == 2) {
employee.setManager(cell.getStringCellValue());
}
else if (cell.getColumnIndex() == 3) {
employee.setOnsite(cell.getStringCellValue());
}
break;
}
}
String sql1 = "INSERT INTO PMO(Id,Employee,Manager,Onsite) VALUES(?, ?, ?, ?)";
getjdbcTemplate().update(sql1, new Object[]{employee.getId(),employee.getEmployeeName(),
employee.getManager(),employee.getOnsite()});
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
myoutput
ID Employee Manager Onsite
1 raju ram offsore
It is happening because the spreadsheet returns the date cell value as integer. You need to check if your cell contains date, and work accordingly. This can be done by using DateUtil class. For e.g.
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first/desired sheet from the workbook
HSSFSheet sheet = workbook.ge`enter code here`tSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue() + "\t\t\t\t");
} else {
System.out.println(cell.getNumericCellValue() + "\t\t\t\t");
}
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t\t\t");
break;
// case Cell.CELL_TYPE_BLANK:
// System.out.println("0"+ "\t\t");
// break;
}
}
System.out.println("");
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Earlier I was using SAX parser for export to excel. Now I am not able to get data using Apache POI, Any suggestion???
This String in XML contains all the data which I retrieved through farpoint grid tech and set in the form in action class.
private void parseXML(String inXML) {
/* // get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
// get a new instance of parser
SAXParser sp = spf.newSAXParser();
// parse the file
sp.parse(new InputSource(new StringReader(inXML)), this);
} catch (IOException ie) {
}*/
Now I am using this.
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
short rowNum = 0;
short colNum = 0;
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(colNum);
cell.setCellValue(inXML);
**/* Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellValue(inXML);
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}*/**
try {
FileOutputStream out = new FileOutputStream(new File("C:\\Excel.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This program (which is what you posted with added imports, without the comment block, with a literal string instead of the variable inXML and with the path removed from the output file):
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
public class Main {
public Main() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
short rowNum = 0;
short colNum = 0;
HSSFRow row = sheet.createRow(rowNum++);
Cell cell = row.createCell(colNum);
cell.setCellValue("<data>test data</data>");
try {
FileOutputStream out = new FileOutputStream(new File("Excel.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Produced exactly what you would expect: A spreadsheet with <data>test data</data> in cell A1.
Perhaps cell A1 in your spreadsheet is blank because inXML really is blank.
There is a excel file which is having lot of file names in one of its column . I need to write a java code that should read those file names and generate the same in destination.Can any one help me ?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
FileOutputStream outFile =new FileOutputStream(new File("C:\\"+cell.getStringCellValue()));
workbook.write(outFile);
}
System.out.println("");
}
file.close();
/* FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);*/
//outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are some libraries you can use to read excel files. In my case, I chose the Apache POI which you can download for free and then add to your project. Once you added it, create your Document:
HSSFWorkbook workbook = new HSSFWorkbook( new FileInputStream("filename.xls") );
or, if it's an excel document from 2007 or later:
XSSFWorkbook workbook = new XSSFWorkbook( new FileInputStream("filename.xlsx") );
Now you can iterate through each row and read out the first column:
for( Row row : workbook.getSheetAt(0) ) // Go through each row in sheet 0
System.out.println( row.getCell(0).getStringCellValue() );
public class Test {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("D:\\sampleFileNames.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
FileOutputStream outFile= null;
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
Cell cell = cellIterator.next();
File file1 = new File("D:\\Ganesh\\"+cell.getStringCellValue().toString());
if(!file1.createNewFile()) {
System.out.println("File already exists");
/* Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
outFile =new FileOutputStream(new File("D:\\Ganesh\\"+cell.getStringCellValue().toString()));
//workbook.write(outFile);
System.out.println("");
}
file.close();
outFile.close();
/* FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);*/
//outFile.close();
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}