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");
}
}
}
Related
This my input in cell A4 there is a date. How can i get this in my java program as it is . My DateUtil.isCellDateFormated(Cell) not working .
i have used DataFormatter it is giving me no of days.
public String getDataValueAsString(Cell cell){
String value = null;
CellType type = cell.getCellTypeEnum();
DataFormatter dataFormat = new DataFormatter();
CreationHelper ch = null;
switch(type){
case BLANK:
value = "";
break;
case BOOLEAN:
value = String.valueOf(cell.getBooleanCellValue());
break;
case ERROR:
value = dataFormat.formatCellValue(cell);
break;
case FORMULA:
FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator();
value = dataFormat.formatCellValue(cell, evaluator);
break;
case NUMERIC:
if(DateUtil.isCellDateFormatted(cell)){
System.out.println("Cell is date formatted : ");
ch = cell.getSheet().getWorkbook().getCreationHelper();
short formatIndex = ch.createDataFormat().getFormat(cell.getCellStyle().getDataFormatString());
System.out.println("format index : "+formatIndex);
String format = cell.getCellStyle().getDataFormatString();
System.out.println("format : "+format);
}else{
//value = String.valueOf(cell.getNumericCellValue());
value = dataFormat.formatCellValue(cell);
}
break;
case STRING:
value = cell.getStringCellValue();
break;
default:
value = dataFormat.formatCellValue(cell);
}
return value;
}
It seems that you can try to use Cell.html#getDateCellValue() method.
Some quick example:
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.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
public class ExternalCaller {
public static final String MM_DD_YYYY = "MM/dd/yyyy";
public static void main(String... args) throws IOException {
FileInputStream file = new FileInputStream(new File("D:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int cellType = cell.getCellType();
try {
determineValue(cellType, cell);
} catch (UnsupportedOperationException ex) {
System.out.println(ex.getMessage());
}
}
}
}
public static void determineValue(int cellType, Cell cell) {
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC:
determineDate(cell);
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
default:
throw new UnsupportedOperationException("This type of cell should be additionally implemented");
}
}
private static void determineDate(Cell cell) {
short dataFormat = cell.getCellStyle().getDataFormat();
if (14 == dataFormat) {
Date dateCellValue = cell.getDateCellValue();
System.out.println(new SimpleDateFormat(MM_DD_YYYY).format(dateCellValue));
} else {
System.out.println(new DataFormatter().formatCellValue(cell));
}
}
}
The output for the cell
will be:
123.0546
Killme
78%
11/22/1995
This type of cell should be additionally implemented
1190
Please let me know if it works for you, otherwise I will remove the answer.
Its been a while i m trying to create a excel sheet to store the crawled data in a table format in a excel , the data is fetched from a url and stored in a array list , this data is needed to be stored in a array list `
import java.util.ArrayList;
import com.webscrap4j.WebScrap;
import com.webscrap4j.WebScrapException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
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;
import org.apache.poi.xssf.usermodel.XSSFTable;
public class crawl
{
public static void main(String[] args) throws IOException {
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> bl = new ArrayList<String>();
ArrayList<String> cl = new ArrayList<String>();
WebScrap ws = new WebScrap();
ws.setUrl("https://www.pepperfry.com/hardware-electricals-power-storage-ups-inverters.html");
try
{
ws.startWebScrap();
//al = ws.getImageTagData("img", "title");
al = ws.getSingleHTMLScriptData("<div class='card-body-title hidden-txt'>", "</div>");
bl = ws.getSingleHTMLScriptData("<span class='strike'>", "</span>");
cl = ws.getSingleHTMLScriptData("<p class='card-body-price txt-red'>", "</p>");
/* FileOutputStream fos=new FileOutputStream("/Users/parthpatil/Documents/11.xls");
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFSheet Sheet = workBook.createSheet("products");
//XSSFTable my_table = Sheet.createTable();
HSSFRow row;
HSSFCell cell;
CreationHelper helper = workBook.getCreationHelper();
Row header = Sheet.createRow(0);
header.createCell(0).setCellValue("Product Name");
header.createCell(1).setCellValue("Product Price");
header.createCell(2).setCellValue("Product MRP");
for(int i=0;i<al.size();i++){
row = Sheet.createRow((short) i);
cell = row.createCell(i);
System.out.println(al.get(i));
cell.setCellValue(al.get(i).toString());
}
System.out.println("Done");
workBook.write(fos);
*/
for (String adata : al)
{
System.out.println("the product are:- " + adata);
}
for (String bdata : bl)
{
System.out.println("the MRp are:- " + bdata);
}
for (String cdata : cl)
{
System.out.println("the selling price is:- " + cdata);
}
} catch (WebScrapException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your code is globally correct it has only some little mistakes, here is how it could be done with your code:
// Use the try-with-resource statement to close all the resources properly
try (HSSFWorkbook workBook = new HSSFWorkbook();
FileOutputStream fos = new FileOutputStream("/Users/parthpatil/Documents/11.xls")) {
// Create the Sheet
HSSFSheet Sheet = workBook.createSheet("products");
// Create the first row corresponding to the header
Row header = Sheet.createRow(0);
header.createCell(0).setCellValue("Product Name");
header.createCell(1).setCellValue("Product Price");
header.createCell(2).setCellValue("Product MRP");
// Ensure that all the List have the same size otherwise throw an exception
if (al.size() != bl.size() || al.size() != cl.size())
throw new IllegalStateException("Some data is missing");
// Iterate over all the list an create the rows of data
for(int i = 0; i < al.size(); i++){
// Create the current starting from 1 to al.size()
HSSFRow row = Sheet.createRow((short) i + 1);
// Cell of the Product Name
row.createCell(0).setCellValue(al.get(i));
// Cell of the Product Price
row.createCell(1).setCellValue(cl.get(i));
// Cell of the Product MRP
row.createCell(2).setCellValue(bl.get(i));
}
// Write the result into the file
workBook.write(fos);
}
I want to read a .xlsx file and display the content. For that purpose I added these libraries:
xmlbeans-2.6.0.jar
poi-3.11-20141221.jar
poi-examples-3.11-20141221.jar
poi-excelant-3.11-20141221.jar
poi-ooxml-3.11-20141221.jar
poi-ooxml-schemas-3.11-20141221.jar
poi-scratchpad-3.11-20141221.jar
I get this error:
Usage: BiffDrawingToXml [options] inputWorkbook Options:
-exclude-workbook exclude workbook-level records -sheet-indexes output sheets with specified indexes -sheet-namek output sheets with specified name
Could anyone tell me what's happening please? Here is the code:
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.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;
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;
/**
* #author giftsam
*/
public class Principal
{
public static void main(String[] args) throws IOException
{
File myFile = new File("C://2feb15.xlsx");
FileInputStream fis = new FileInputStream(myFile);
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = mySheet.iterator();
// Traversing over each row of XLSX file
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_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default :
}
}
System.out.println("");
}
}
}
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 }
I'm trying to use POI.APACHE to edit excel files in java. I have to convert a .xls to .xlsx because I need to send the file to sharepoint. Thats why it just can't be renamed with a different extension. How would I go about this? I couldn't find any examples on their site. Thanks
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* Partial copy of one of style and data..
*
* #author jcalfee
*/
public class xls2xlsx {
/**
* #param args
* #throws InvalidFormatException
* #throws IOException
*/
public static void main(String[] args) throws InvalidFormatException,
IOException {
String inpFn = args[0];
String outFn = args[1];
InputStream in = new BufferedInputStream(new FileInputStream(inpFn));
try {
Workbook wbIn = new HSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new XSSFWorkbook();
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(0);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(
cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
{
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
}
cellOut.setCellComment(cellIn.getCellComment());
// HSSFCellStyle cannot be cast to XSSFCellStyle
// cellOut.setCellStyle(cellIn.getCellStyle());
}
}
}
OutputStream out = new BufferedOutputStream(new FileOutputStream(
outF));
try {
wbOut.write(out);
} finally {
out.close();
}
} finally {
in.close();
}
}
}