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
I have a spreadsheet based on which I have to generate a xml file. the file should respect a particular XSD structure and I have to do from Java.
The XML mapping is not working in excel because of "list of lists " issue.
what would be an ideal approach in java to create , domparser or jaxb ?
Any reference is helpful
Here is my code
package exceltoXML;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
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.eclipse.jgit.*;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class readExcel_class1 {
public static Properties properties;
public static Enumeration<?> en;
public static String SourcePath;
public static String targetPath;
public static Map<String, String> propertiesCaseInsensitiveMap;
public static List<foldermap> foldermaps;
public static void main(String[] args) throws IOException, ParserConfigurationException, TransformerException {
// TODO Auto-generated method stub
Writer writer = null;
try {
foldermaps = new ArrayList<foldermap>();
properties=loadProperties(args[0]);
en=properties.propertyNames();
propertiesCaseInsensitiveMap=new TreeMap<String,String>(String.CASE_INSENSITIVE_ORDER);
while(en.hasMoreElements()){
String key=(String)en.nextElement();
propertiesCaseInsensitiveMap.put(key, properties.getProperty(key));
}
SourcePath=propertiesCaseInsensitiveMap.get("sourcepath");
targetPath=propertiesCaseInsensitiveMap.get("targetPath");
System.out.println("Source Path is "+ SourcePath + " and Target path is " + targetPath);
String fileName = "export_"+new Date().getTime() + ".json";
System.out.println("Output filename is " + fileName);
//System.out.println("Hi");
File myFile = new File("C:\\Users\\abcdra\\Desktop\\cicd\\git_push.xlsm");
FileInputStream fis = new FileInputStream(myFile);
String sourceFileName = SourcePath+fileName;
String targetFileName = targetPath+fileName;
System.out.println("Source FileName : " + sourceFileName);
System.out.println("Target FileName : " + targetFileName);
File file = new File(sourceFileName);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder1 = factory.newDocumentBuilder();
Document document = builder1.newDocument();
Element rootElement = document.createElement("importParams");
document.appendChild(rootElement);
rootElement.setAttribute("xmlns", "http://www.abc.io/oie/importControl/9" );
writer = new BufferedWriter(new FileWriter(file));
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(1);
Iterator<Row> rowIterator = mySheet.iterator();
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
foldermap foldermap = new foldermap();
while (rowIterator.hasNext()) {
//System.out.println("Current Row Number : " + rowIterator.next().getRowNum());
Row row = rowIterator.next();
if(row.getRowNum()==0 ){
continue; //just skip the rows if row number is 0
}
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
ArrayList<String> rowData = new ArrayList<String>();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
//System.out.println ("String: " + cell.getRichStringCellValue ());
rowData.add(cell.getRichStringCellValue() + "");
//System.out.println("Inside cells");
if (cell.getColumnIndex() ==0 )
{
foldermap.setSourceProject(cell.getStringCellValue());
System.out.println("source project " + foldermap.getSourceProject());
}
if (cell.getColumnIndex() ==1 )
{
foldermap.setSourceFolderPath (cell.getStringCellValue());
}
if (cell.getColumnIndex() ==2 )
{
foldermap.setTargetProject(cell.getStringCellValue());
}
if (cell.getColumnIndex() ==3 )
{
foldermap.setTargetFolderPath( cell.getStringCellValue());
}
if (cell.getColumnIndex() ==4 )
{
foldermap.setRecursive(cell.getStringCellValue());
System.out.println("Recursive value " + foldermap.getRecursive());
}
if (cell.getColumnIndex() ==5 )
{
foldermap.setRecursive(cell.getStringCellValue());
System.out.println("Recursive value " + foldermap.getRecursive());
}
break;
case NUMERIC:
System.out.println ("String: " + cell.getNumericCellValue ());
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default :
}
}
// System.out.println("\n");
writer.write("\n ");
foldermaps.add(foldermap);
}
System.out.println("Writing to text file is completed...");
if (writer != null) {
writer.close();
}
TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
//create target path if it does not exist
Element foldermaps1 = document.createElement("folderMaps");
rootElement.appendChild(foldermaps1);
System.out.println("Number of foldermap are " + foldermaps.size());
for (foldermap fm : foldermaps)
{
System.out.println("Source Project is " + fm.getSourceProject());
Element fmap = document.createElement("folderMap");
foldermaps1.appendChild(fmap);
fmap.setAttribute("sourceProject", fm.getSourceProject());
fmap.setAttribute("sourceFolderPath", fm.getSourceFolderPath());
fmap.setAttribute("targetProject", fm.getTargetProject());
fmap.setAttribute("targetFolderPath", fm.getTargetFolderPath());
fmap.setAttribute("recursive", fm.getRecursive());
}
StreamResult result = new StreamResult(new File("C:\\Users\\abcdra\\Desktop\\eclipse_workspace_64\\abc.xml"));
transformer.setOutputProperty
(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
System.out.println("Parameter file successfully created");
}
catch(IOException ex )
{
ex.printStackTrace();
}
}
public static Properties loadProperties(String filename){
Properties props = new Properties();
InputStream input = null;
try {
input = new FileInputStream(filename);
props.load(input);
System.out.println("Loaded properties from: " + filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
public static void fileCopy (File sourceDirectory , File targetDirectory)
{
try {
Files.copy(sourceDirectory.toPath(),targetDirectory.toPath());
}
catch(Exception e)
{
System.out.println("Error" + e);
}
}
}
The input is like
I am getting the output like
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<importParams xmlns="http://www.informatica.com/oie/importControl/9">
<folderMaps>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
</folderMaps>
</importParams>
Both elements have value unknown1 , so the last element is repeating ,any idea how to avoid that. the output I am expecting is
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<importParams xmlns="http://www.informatica.com/oie/importControl/9">
<folderMaps>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown" targetFolderPath="import" targetProject="Unknown"/>
<folderMap recursive="truth" sourceFolderPath="Hive" sourceProject="Unknown1" targetFolderPath="import" targetProject="Unknown"/>
</folderMaps>
</importParams>
There is quite a bit of code here, but I think the issue is that the foldermap is not being created new each time inside the row loop.
foldermap foldermap = new foldermap();
while (rowIterator.hasNext()) {
...
foldermaps.add(foldermap);
}
So the foldermap is being updated, but added multiple times.
Move the new foldermap(); inside the while loop so that on each row, there is a new entry.
I think, if I read the code correctly, you can do:
while (rowIterator.hasNext()) {
foldermap foldermap = new foldermap();
...
As the foldermap does not need scope outside of the while loop for the rowIterator.
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");
}
}
}
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("");
}
}
}