values are populating with 2 only - java

I'm a newbie to java & I'm trying to read numeric data from a text file & I want to write each number in a separate cell in an Excel spreadsheet.
Input data is as below:(abc.txt)
3008,45,14,277,10,6371,223,208,116,3036,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,‌​0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,2 2893,114,16,108,30,5066,245,223,102,4340,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0‌​,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,2
I want each value in a different cell. I'm using Apache POI for using excel sheets. This is what I'm able to code till now
package com.example.practise;
import java.io.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
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;
public class MultivariateDT {
public static void main(String[] args) throws IOException{
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:/Users/419803/Desktop/abc.txt"));
FileOutputStream out = new FileOutputStream("C:/Users/419803/Desktop/workbook.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("new sheet");
Row row = null;
Cell cell = null;
String line = null;
String delimiter = ",";
while ((line = bufferedReader.readLine()) != null)
{
String[] temp=null;
String str = " ";
temp = line.split(delimiter);
for(int i =0; i < temp.length ; i++)
{
str = temp[i] + str;
int rownum;
for (rownum =0; rownum < 100; rownum++)
{
row = sheet1.createRow(rownum);
for (int cellnum =0; cellnum <temp.length; cellnum ++)
{
cell = row.createCell(cellnum);
cell.setCellValue(temp[i]);
}
}
}
System.out.println();
}
wb.write(out);
out.close();
}
}
No.of rows & cells that have to be created are correct, but data in excel file is wrong.
In excel file only showing 2,2,2,2 so on.
Can any one please help me??

I think you have too many for-loops with which you are iterating too much, i.e. first you loop over all items in the line, for these you create 100 rows and in each row you iterate overa all items in the line again, creating rows, bug in setCellValue() you are using temp[i], not temp[cellnum], so you are first creating 100 rows with temp[0], then 100 rows with all temp[1], ...
It depends on how the resulting spreadsheet should look like, but I would try to adjust the for-loops accordingly, e.g. for one row per line you would remove the outer too for-loops, for 100 rows per line you would remove the single outer for-loop.

Related

Apache POI recording only 1 row in the spreadsheet

I am using selenium and java to scrape data on a specific site, but with the code below I can write only 1 data in the spreadsheet, it is not recording all the data in sequence as it should be.
I can't structure the loop correctly.
public void gravarDados() throws IOException {
int i = 0;
File localPlanilha = new File("tools/resultado_da_pesquisa.xlsx");
FileInputStream planilhaExistente = new FileInputStream(localPlanilha);
XSSFWorkbook plan = new XSSFWorkbook(planilhaExistente);
XSSFSheet sheetExistente = plan.getSheetAt(0);
for (int i = 0; i < inicio; i++) {
// Writing data
sheetExistente.getRow(2).createCell(5).setCellValue(TitulosHoteis.get(i).getText());
FileOutputStream fechandoArquivo = new FileOutputStream(localPlanilha);
plan.write(fechandoArquivo);
}
}
Currently you are getting only the 0th element.
You need to iterate the below with a for loop
TitulosHoteis.get(i).getText());
to write the result to rows and columns.
Please modify it as below
for (int i = 0; i < inicio; i++) {
// Writing data
sheetExistente.getRow(i+2).createCell(5).setCellValue(TitulosHoteis.get(i).getText());
}
FileOutputStream fechandoArquivo = new FileOutputStream(localPlanilha);
plan.write(fechandoArquivo);
As mentioned before you're not iterating over the rows as the row number stays the same in your code, however there is also another problem with your code. You need to check if a row exists and if it doesn't create it before you can set a cell value of that row.
It should look something like this:
for (int i = 0; i < inicio; i++) {
Row row = sheetExistente.getRow(2+i);
if (row == null) sheetExistente.createRow(2+i);
sheetExistente.getRow(2 + i).createCell(5).setCellValue(TitulosHoteis.get(i).getText());
}

dataprovider excel file reading how skip first row

Heading
how to skip first row , if i make i=1 in for loop giving null null for
first row values
how to skip first row , if i make i=1 in for loop giving null null for
first row values
how to skip first row , if i make i=1 in for loop giving null null for
first row values
package excel2;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProvider2 {
XSSFSheet sheet;
int row ;
int col;
#Test(dataProvider = "excel")
public void tc_01(String Srno, String name,String add) {
System.out.println("name :" + Srno + "\t palce :" + name + " add :
"+add);
}
/**
* #author pritesh
* #return
* #throws IOException
*/
#DataProvider(name = "excel")
public Object[][] abc() throws IOException {
FileInputStream fl = new
FileInputStream("C:\\Users\\pritesh\\Desktop\\x22.xlsx");
XSSFWorkbook book = new XSSFWorkbook(fl);
sheet = book.getSheetAt(0);
row = sheet.getLastRowNum()+1;
col = sheet.getRow(0).getLastCellNum();
Object[][] obj = new Object[row][col];
for (int i = 1; i <row; i++) {
XSSFRow rw = sheet.getRow(i);
for (int j = 0; j <col; j++) {
obj[i][j] = rw.getCell(j).getStringCellValue();
}
}
return obj;
}
}
all the row except first row of excel sheet should be read and show in
console
all the row except first row of excel sheet should be read and show in
console
all the row except first row of excel sheet should be read and show in
console
all the row except first row of excel sheet should be read and show in
console
Try to add the below line after first for the loop
if (i=0){ continue; }

Excel formula on the current value/cell POI

I'm working on POI application in order to manipulate excel file.
In fact the user is giving a formula and files and I am applying the formula on a output file.The formula have to modify the value of the column on the cell.
For example on the columns B, I want to apply on all my column a formula.
The user is giving to me LEFT(x,2), and I have to apply this to all the columns.
(x is defining all the columns)
But when I am applying the formula I got the formula as a String. I try to pass the cell value at the formula but of course it is not working...
I think I should copy all my data into a another excel file, work on it and copy paste them in the output file or their is another way ?
Regards,
Code:
for (int i = 0; i < cell[0].length; i++){ //Checking the header
for (int j = 0; j < ruleArray.length; j++){ //Checking the Header of the array with the rule to apply
if (cell[0][i].toString().equals(ruleArray[j][0])){ //Comparing
String testF = ruleArray[j][1];
if (testF.contains("X") || testF.contains("x")){ //Replacing X with value for the formula
for (int k = 0; k < cell.length; k++){
indexT = cell[0][i].getColumnIndex();
indexC = cell[k][i].getRowIndex()+1;
String colLetter = CellReference.convertNumToColString(indexT);
formula = testF.replace("x", colLetter+indexC);
cell[k][i].setCellType(CellType.FORMULA);
cell[k][i].setCellFormula(formula);
}
}
}
}
}
I am not rewrite your code but you can take a help from this. Create a excel file with column City and Formula and then run this code. I have attached some snapshot of excel file. I thin kit will help you. LEFT(X,2) only parse first two char from a string
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class TestProblem
{
public static void main(String[] args) throws IOException {
InputStream inp = null;
inp = new FileInputStream("E:\\Projects\\PoiAdvanceExample\\stackProblem.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
int rowsCount = sheet.getLastRowNum();
int columnCount = sheet.getRow(0).getLastCellNum();
String[][] inputData = new String[rowsCount+1][columnCount];
for (int i = 0; i <= rowsCount; i++) {
Row row = sheet.getRow(i);
int colCounts = row.getLastCellNum();
for (int j = 0; j < colCounts; j++) {
Cell cell = row.getCell(j);
if(cell.getCellType() == CellType.NUMERIC) {
inputData[i][j] = Double.toString(cell.getNumericCellValue());
}
if(cell.getCellType() == CellType.FORMULA) {
inputData[i][j] = cell.getCellFormula();
}
if(cell.getCellType() == CellType.STRING) {
inputData[i][j] = cell.getStringCellValue();
}
}
}
writeData(inputData);
}
private static void writeData(String[][] inputData) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
int r = 0;
for (String[] dataRow : inputData) {
Row row = sheet.createRow(r++);
int column = 0;
for (String dataCell : dataRow) {
Cell cell = row.createCell(column++);
if (r == 1 || column == 1) cell.setCellValue(dataCell);
else if (column == 2) {
CellReference cellReference = new CellReference(cell);
String thisR = cellReference.getCellRefParts()[1];
cell.setCellFormula("LEFT(A" + thisR + ",2)");
}
}
}
FileOutputStream fileOut = new FileOutputStream("stackProblem.xlsx");
workbook.write(fileOut);
workbook.close();
}
}
Excel file before run will be like this.
Excel file after run this code will be like this.

converting excel data to JSON format

I am trying to convert excel data into JSON format. but the problem is I have excel sheets which are linked to multiple excel sheet. like example root.xlsx which contains
id, name, phone,department,category,age fields
and where department field refers to department.xlsx which contains
dname, did, dtype
and category fields refers to category.xlsx which contains
catid,catname,cattype,
how to convert it to JSON if the data format is like this?
Jars Required
commons-beanutils-1.8.3.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
json-lib-2.4-jdk15.jar
poi
Sample code
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.json.Json;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import net.sf.json.JSONObject;
public class ReadExcelDataWithDynamicColumn {
public static void main(String[] args)
{
// You can specify your excel file path.
String excelFilePath = "/Users/zhaosong/Documents/WorkSpace/EmployeeInfo.xls";
// This method will read each sheet data from above excel file and create a JSON and a text file to save the sheet data.
creteJSONAndTextFileFromExcel(excelFilePath);
}
/* Read data from an excel file and output each sheet data to a json file and a text file.
* filePath : The excel file store path.
* */
private static void creteJSONAndTextFileFromExcel(String filePath)
{
try{
/* First need to open the file. */
FileInputStream fInputStream = new FileInputStream(filePath.trim());
/* Create the workbook object to access excel file. */
//Workbook excelWookBook = new XSSFWorkbook(fInputStream)
/* Because this example use .xls excel file format, so it should use HSSFWorkbook class. For .xlsx format excel file use XSSFWorkbook class.*/;
Workbook excelWorkBook = new HSSFWorkbook(fInputStream);
// Get all excel sheet count.
int totalSheetNumber = excelWorkBook.getNumberOfSheets();
// Loop in all excel sheet.
for(int i=0;i<totalSheetNumber;i++)
{
// Get current sheet.
Sheet sheet = excelWorkBook.getSheetAt(i);
// Get sheet name.
String sheetName = sheet.getSheetName();
if(sheetName != null && sheetName.length() > 0)
{
// Get current sheet data in a list table.
List<List<String>> sheetDataTable = getSheetDataList(sheet);
// Generate JSON format of above sheet data and write to a JSON file.
String jsonString = getJSONStringFromList(sheetDataTable);
String jsonFileName = sheet.getSheetName() + ".json";
writeStringToFile(jsonString, jsonFileName);
// Generate text table format of above sheet data and write to a text file.
String textTableString = getTextTableStringFromList(sheetDataTable);
String textTableFileName = sheet.getSheetName() + ".txt";
writeStringToFile(textTableString, textTableFileName);
}
}
// Close excel work book object.
excelWorkBook.close();
}catch(Exception ex){
System.err.println(ex.getMessage());
}
}
/* Return sheet data in a two dimensional list.
* Each element in the outer list is represent a row,
* each element in the inner list represent a column.
* The first row is the column name row.*/
private static List<List<String>> getSheetDataList(Sheet sheet)
{
List<List<String>> ret = new ArrayList<List<String>>();
// Get the first and last sheet row number.
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
if(lastRowNum > 0)
{
// Loop in sheet rows.
for(int i=firstRowNum; i<lastRowNum + 1; i++)
{
// Get current row object.
Row row = sheet.getRow(i);
// Get first and last cell number.
int firstCellNum = row.getFirstCellNum();
int lastCellNum = row.getLastCellNum();
// Create a String list to save column data in a row.
List<String> rowDataList = new ArrayList<String>();
// Loop in the row cells.
for(int j = firstCellNum; j < lastCellNum; j++)
{
// Get current cell.
Cell cell = row.getCell(j);
// Get cell type.
int cellType = cell.getCellType();
if(cellType == CellType.NUMERIC.getCode())
{
double numberValue = cell.getNumericCellValue();
// BigDecimal is used to avoid double value is counted use Scientific counting method.
// For example the original double variable value is 12345678, but jdk translated the value to 1.2345678E7.
String stringCellValue = BigDecimal.valueOf(numberValue).toPlainString();
rowDataList.add(stringCellValue);
}else if(cellType == CellType.STRING.getCode())
{
String cellValue = cell.getStringCellValue();
rowDataList.add(cellValue);
}else if(cellType == CellType.BOOLEAN.getCode())
{
boolean numberValue = cell.getBooleanCellValue();
String stringCellValue = String.valueOf(numberValue);
rowDataList.add(stringCellValue);
}else if(cellType == CellType.BLANK.getCode())
{
rowDataList.add("");
}
}
// Add current row data list in the return list.
ret.add(rowDataList);
}
}
return ret;
}
/* Return a JSON string from the string list. */
private static String getJSONStringFromList(List<List<String>> dataTable)
{
String ret = "";
if(dataTable != null)
{
int rowCount = dataTable.size();
if(rowCount > 1)
{
// Create a JSONObject to store table data.
JSONObject tableJsonObject = new JSONObject();
// The first row is the header row, store each column name.
List<String> headerRow = dataTable.get(0);
int columnCount = headerRow.size();
// Loop in the row data list.
for(int i=1; i<rowCount; i++)
{
// Get current row data.
List<String> dataRow = dataTable.get(i);
// Create a JSONObject object to store row data.
JSONObject rowJsonObject = new JSONObject();
for(int j=0;j<columnCount;j++)
{
String columnName = headerRow.get(j);
String columnValue = dataRow.get(j);
rowJsonObject.put(columnName, columnValue);
}
tableJsonObject.put("Row " + i, rowJsonObject);
}
// Return string format data of JSONObject object.
ret = tableJsonObject.toString();
}
}
return ret;
}
/* Return a text table string from the string list. */
private static String getTextTableStringFromList(List<List<String>> dataTable)
{
StringBuffer strBuf = new StringBuffer();
if(dataTable != null)
{
// Get all row count.
int rowCount = dataTable.size();
// Loop in the all rows.
for(int i=0;i<rowCount;i++)
{
// Get each row.
List<String> row = dataTable.get(i);
// Get one row column count.
int columnCount = row.size();
// Loop in the row columns.
for(int j=0;j<columnCount;j++)
{
// Get column value.
String column = row.get(j);
// Append column value and a white space to separate value.
strBuf.append(column);
strBuf.append(" ");
}
// Add a return character at the end of the row.
strBuf.append("\r\n");
}
}
return strBuf.toString();
}
/* Write string data to a file.*/
private static void writeStringToFile(String data, String fileName)
{
try
{
// Get current executing class working directory.
String currentWorkingFolder = System.getProperty("user.dir");
// Get file path separator.
String filePathSeperator = System.getProperty("file.separator");
// Get the output file absolute path.
String filePath = currentWorkingFolder + filePathSeperator + fileName;
// Create File, FileWriter and BufferedWriter object.
File file = new File(filePath);
FileWriter fw = new FileWriter(file);
BufferedWriter buffWriter = new BufferedWriter(fw);
// Write string data to the output file, flush and close the buffered writer object.
buffWriter.write(data);
buffWriter.flush();
buffWriter.close();
System.out.println(filePath + " has been created.");
}catch(IOException ex)
{
System.err.println(ex.getMessage());
}
}
}
for more details visit https://www.dev2qa.com/convert-excel-to-json-in-java-example/

reading excel rows properly

I am trying to read multiple rows of data from .xlsx file. The output in console shows the all values one below another.
Issue is they are not being displayed in the table like manner as they are displayed in source excel sheet.
My excel file is .xlsx, so I am coding with XSSF POI api.
It contains two columns(Name and Score) with 5 rows total.
Console output looks like this
Name
Score
TOM
1
DICK
2
HARRY
3
JERRY
4
I want it to print like this:
Name Score
TOM 1
DICK 2
HARRY 3
JERRY 4
code:
package gmailExcel;
import java.io.FileInputStream;
import java.io.IOException;
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;
public class ReadXl {
public static void main(String[] args) throws IOException {
// Locate xl file.
FileInputStream fis = new FileInputStream
("File location on local host");
// Load file, workbook and sheet.
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet("sheetName");
// Declare row and cell variable.
XSSFRow row;
XSSFCell cells;
// Get row and column count.
int rowCount = ws.getLastRowNum();
int colCount = ws.getRow(0).getLastCellNum();
// Iterate over rows and columns.
for(int r = 0; r < rowCount; r++) {
row = ws.getRow(r);
for(int c = 0; c < colCount; c++) {
cells = row.getCell(c);
// Output the values from Excel sheet.
String cellval = cells.toString();
System.out.println(cellval);
}
}
}
}
The issue is in your nested for-loop. In each iteration, you are printing the value with a newline after it. What you want to do is to print the newline only after you've printed the cell in the second column I presume.
This can be accomplished by printing the newline outside the nested loop like this:
for (int r = 0; r < rowCount; r++) {
for (int c = 0; c < colCount; c++) {
cells = row.getCell(c);
String cellval = cells.toString();
System.out.print(" | " + cellval); //New line IS NOT printed
}
System.out.println(" |"); //New line IS printed
}

Categories