Trying to print xlsx content with Apache POI - java

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("");
}
}
}

Related

I try to retain the input but InvalidFormatException was thrown

I would like to retain the data in the existing excel file.After that then try to output something to this file.But I got an error.
I have been searching the answer but none of it matches my situation.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class TryHyperlink{
public static void main(String[] args) {
File in = new File("D:\\Test1.xlsx");
try {
FileInputStream fin = new FileInputStream(in);
//read input
XSSFWorkbook wb;
wb = new XSSFWorkbook(fin);//The StackTrace shows that the error is here
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator();
//iterate through every row and cell
while(rowItr.hasNext()) {
Row row = rowItr.next();
Iterator<Cell> cellItr = row.iterator();
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
}
}
fin.close();
//close the input stream so output stream can write
FileOutputStream fout = new FileOutputStream(in);
wb.write(fout);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Edit:
After referring to Alex Richter Comment,I closed the output stream and the error gone. Now Another error come out:
WARNING: An illegal reflective access operation has occurred and so on(the link of the photo at the bottom of the question)
package net.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class TryHyperlink{
public static void main(String[] args) {
File in = new File("D:\\penril.xlsx");
try {
FileInputStream fin = new FileInputStream(in);
XSSFWorkbook wb;
wb = new XSSFWorkbook(fin);
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator();
while(rowItr.hasNext()) {
Row row = rowItr.next();
Iterator<Cell> cellItr = row.iterator();
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
cell.setCellValue(cell.getNumericCellValue());
}
}
fin.close();
FileOutputStream fout = new FileOutputStream(in);
wb.write(fout);
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```package net.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class TryHyperlink{
public static void main(String[] args) {
File in = new File("D:\\penril.xlsx");
try {
FileInputStream fin = new FileInputStream(in);
XSSFWorkbook wb;
wb = new XSSFWorkbook(fin);
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator();
while(rowItr.hasNext()) {
Row row = rowItr.next();
Iterator<Cell> cellItr = row.iterator();
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
cell.setCellValue(cell.getNumericCellValue());
}
}
fin.close();
FileOutputStream fout = new FileOutputStream(in);
wb.write(fout);
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}```
[1]: https://i.stack.imgur.com/WTOn3.png

Getting this error: Message: java.lang.IllegalStateException: Cannot get a text value from a numeric cell

import com.itko.lisa.vse.stateful.model.TransientResponse;
import com.itko.lisa.vse.stateful.model.Response;
import com.itko.util.ParameterList;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.lang.String;
import org.apache.log4j.*;
import groovy.util.logging.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
FileInputStream fileInputStream = new FileInputStream("C:/Softwares/LISA/CBO_CurrentBalance1/Data/BalanceReport.xlsx");
//FileInputStream fileInputStream = new FileInputStream("/home/lisa-user/Data/CBOPayment.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream)
XSSFSheet sheet = workbook.getSheet("Sheet1");
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
row = (XSSFRow) rows.next();
Iterator cells = row.cellIterator();
AccountNumber1 = testExec.getStateObject("AccountNumber1")
AccountNumber2 = testExec.getStateObject("AccountNumber2")
if (AccountNumber1 == cells.next().getStringCellValue()) {
if(cells.hasNext()) {
Balance = cells.next().getNumericCellValue();
testExec.setStateValue("Balance1", Balance);
}
}
if (AccountNumber2 == cells.next().getStringCellValue()) {
if (cells.hasNext()) {
Balance = cells.next().getNumericCellValue();
testExec.setStateValue("Balance2", Balance);
}
}
}
you need something like this :
don't get confused with the naming convention as this is one of my code.
the problem is
DataFormatter fmt = new DataFormatter();
String _charges = fmt.formatCellValue(sheet.getRow(45).getCell(CellReference.convertColStringToIndex("D")));
what you are doing is trying to fetch a numeric value from the sheet whereas it is saved as a String so you need to convert it to String before you can use it. The code i have pasted is not the exact solution but i hope you might get the hint about the solution.

Want to display the contents of csv/xlsx files in Object

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");
}
}
}

insert data stored in array list in excel using java

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);
}

.xls convert to xlsx using java and POI APACHE

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();
}
}
}

Categories

Resources