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();
}
}
}
Related
I have some records with header in my excel sheet.I want to read all the records and write to the docx file along with header using java.Thanks for the helps.
Able to write one excel to other excel file but failed to write in docx file.
I have try this way but the word file is generated as corrupted.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class ExcelReaderDemo {
public static final String SAMPLE_XLSX_FILE_PATH =
"C:/XLXSToDocx/Roaster.xlsm";
public static final String FILE_PATH ="C:/XLXSToDocx/writeExcel.docx";
public static void main(String[] args) throws IOException,
InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new
File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + "
Sheets : ");
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
try {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println();
}
workbook.close();
}
}
I would suggest to use Apache Poi lib (https://poi.apache.org/)
Rewrite your code like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelReaderDemo {
public static final String SAMPLE_XLSX_FILE_PATH = "C:/XLXSToDocx/Roaster.xlsm";
public static final String FILE_PATH = "C:/XLXSToDocx/writeExcel.docx";
public static void main(String[] args) throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
try {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE !!!");
}
}
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());
}
}
}
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.
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 }
The scenario is roughly this:
I have a java program with several methods getting called randomly.
The first method will create an xls file using apache POI and will put the headers for the columns.
All the other methods has to write a record into this file.
The final method will first mail the created xls and then delete the xls.
For above scenario is the below approach correct:
1) Create the file and put the header names in the first method:
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("First Sheet");
Row row = sheet.createRow((short)0);
row.createCell(1).setCellValue(createHelper.createRichTextString("First Column"));
row.createCell(2).setCellValue(createHelper.createRichTextString("Second Column"));
row.createCell(3).setCellValue(createHelper.createRichTextString("Third Column"));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
2) In the remaining methods put the records:
I am not sure of the code here. I know that I can reach the end of the sheet using getRowCount method and then add the new row. But I could not find any example code.
Also, how to access the existing xls file ?
3) In the last method, the file will be mailed and then deleted.
Do I need to perform any other steps before deleting the file ?
This was what I was looking for:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
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.ss.usermodel.WorkbookFactory;
public class PoiWriteExcelFile {
public void methodOne() {
System.out.println("Into method one!");
Workbook wb = new HSSFWorkbook();
Font f = wb.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
CellStyle cs = wb.createCellStyle();
cs.setFont(f);
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("First Sheet");
Row row = sheet.createRow((short) 0);
Cell c = null;
c = row.createCell(0);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("First Column"));
c = row.createCell(1);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("Second Column"));
c = row.createCell(2);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("Third Column"));
// Write the output to a file
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method one!");
}
public void methodTwo() {
System.out.println("Into method two!");
InputStream inp;
try {
inp = new FileInputStream("C:\\TestData\\POI\\poi-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
Cell c = null;
CreationHelper createHelper = wb.getCreationHelper();
c = row.createCell(0);
c.setCellValue(createHelper.createRichTextString("First Row First value"));
c = row.createCell(1);
c.setCellValue(createHelper.createRichTextString("First Row Second value"));
c = row.createCell(2);
c.setCellValue(createHelper.createRichTextString("First Row Third value"));
FileOutputStream fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method two!");
}
public void methodThree() {
System.out.println("Into method three!");
InputStream inp;
try {
inp = new FileInputStream("C:\\TestData\\POI\\poi-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
Cell c = null;
CreationHelper createHelper = wb.getCreationHelper();
c = row.createCell(0);
c.setCellValue(createHelper.createRichTextString("Second Row First value"));
c = row.createCell(1);
c.setCellValue(createHelper.createRichTextString("Second Row Second value"));
c = row.createCell(2);
c.setCellValue(createHelper.createRichTextString("Second Row Third value"));
FileOutputStream fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method three!");
}
public void methodFour() {
System.out.println("Into method four!");
File file = new File("C:\\TestData\\POI\\poi-test.xls");
// file.deleteOnExit();
System.out.println("Out of method four!");
}
public static void main(final String[] args) {
PoiWriteExcelFile myObj = new PoiWriteExcelFile();
myObj.methodOne();
myObj.methodTwo();
myObj.methodThree();
myObj.methodFour();
}
}