i have an excel file with merged and formula cell which is using the VLOOKUP(B16,Data!$A$2:$C$7,3,0). In specific cell $40 is appearing as value. but when i try to read the value it is reading only 40 and skipping the $ part.
public static void main(String[] args) {
try {
String excelFilePath = "D:\\test\\1_sample1_UA Logo Order form update on 2016-12-06.xls";
InputStream input = new BufferedInputStream(new FileInputStream(
excelFilePath));
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
workbook.setForceFormulaRecalculation(true);
Sheet sheet = workbook.getSheetAt(3);
Row row = sheet.getRow(15);
Cell cell = row.getCell(7);
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress region = sheet.getMergedRegion(i); // Region of
// merged
// cells
int colIndex = region.getFirstColumn();
int rowNum = region.getFirstRow();
if (region.isInRange(15, 7)) {
CellReference cellReference = new CellReference("H15");
Row row2 = sheet.getRow(cellReference.getRow());
Cell cell2 = row2.getCell(cellReference.getCol());
// formulla evaluato
FormulaEvaluator forEvaluator = workbook
.getCreationHelper().createFormulaEvaluator();
workbook.getCreationHelper().createFormulaEvaluator()
.evaluateAll();
workbook.setForceFormulaRecalculation(true);
CellValue cellValue = forEvaluator.evaluate(cell2);
System.out.println("cell string value2 :: "
+ cellValue.formatAsString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Related
Hi I need to store a list of values which I obtained from a webpage using List and Iterator using selenium webdriver, I want to store/write those values in a excel sheet
Link of the website:https://www.zigwheels.com/used-car
I have obtained a list of values under popular car models and I need to store it in a excel sheet using apache poi
Coding starts here:
WebElement li=
driver.findElement(By.xpath("//span[text()='Brand and Model']//parent::div//followingsibling::div//child::div[4]/ul"));
List<WebElement> alloptions=li.findElements(By.tagName("li"));
Iterator<WebElement> itr=alloptions.iterator();
while(itr.hasNext()) {
WebElement lii=itr.next();
String list=lii.getText();
System.out.println(list);
Create file, than sheet, then rows, and fill cells in row:
public void CreateNew_Make_BeckupFile() throws IOException
{
String filePath = "filepath.xls";
File f = new File(filePath);
if (!(f.exists() && f.isFile()))
{
Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file
/*
* CreationHelper helps us create instances of various things like DataFormat,
* Hyperlink, RichTextString etc, in a format (HSSF, XSSF) independent way
*/
CreationHelper createHelper = workbook.getCreationHelper();
for (int p = 0; p < listaTimova.size(); p++) {
// Create a Sheet
// Sheet sheet = workbook.createSheet("Employee");
SheetCreation (workbook, p);
}
// Write the output to a file
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
// Closing the workbook
workbook.close();
outputStream.close();
}
public void SheetCreation (Workbook workbook, int teamNumber)
{
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Sheet Name");
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setFontHeightInPoints((short) 14);
headerFont.setColor(IndexedColors.BLUE.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Create a Row
Row headerRow = sheet.createRow(0);
// Create cells
for (int i = 0; i < columns.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
headerFont.setColor(IndexedColors.BLACK.getIndex());
headerCellStyle.setFont(headerFont);
for (int u = 0; u < listaTimova.get(teamNumber).listaIgracaTima.size(); u++)
{
Row headerRow2 = sheet.createRow(u + 1);
**RowCreation(headerRow2, teamNumber, u, 0);**
}
for(int i = 0; i < columns.length; i++)
{
sheet.autoSizeColumn(i);
}
}
**public void RowCreation(Row row, int teamNumber, int playerNumber, int cellNumber)**
{
row.createCell(cellNumber, CellType.STRING).setCellValue("Any value for cell");
row.createCell(cellNumber+1, CellType.STRING).setCellValue("next cell in row value...");
}
I am printing some string values in excel
In excel currently last string is printing, but I need to print them all row by row
Code
for(String a:arrOfStr)
{
System.out.println(a);
//CustomKeywords.'WriteExcel.demoKey'(a)
CustomKeywords.'WriteExcel.demoKey'(a)
}
keyword
#Keyword
public void demoKey(String name) throws IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\lahiruh\\Katalon Studio\\Project Decypha\\Decypha data files\\Demo1.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
Row row = sheet.createRow(rowCount+);
Cell cell = row.createCell(0);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("C:\\Users\\lahiruh\\Katalon Studio\\Project Decypha\\Decypha data files\\Demo1.xlsx");
workbook.write(fos);
fos.close();
Now I can get the output like(overriding each value and giving last string )
I want to see like
Try this
for(int i = 0; i < arrOfStr.size(); i++)
{
String a = arrOfStr[i];
System.out.println(a);
//CustomKeywords.'WriteExcel.demoKey'(a)
CustomKeywords.'WriteExcel.demoKey'(a,i)
}
#Keyword
public void demoKey(String name, int index) throws IOException{
FileInputStream fis = new FileInputStream("path");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
Row row = sheet.createRow(index + 1);
Cell cell = row.createCell(0);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("path");
workbook.write(fos);
fos.close();
}
}
You have to do in the following manner.
First create a set of rows
Create cell and define the cell data type.
Store the value in the cell
I provide below the structure to store the data row by row.
int rowNumber = 0; // Row number starting with 0
for (i = 0 ; i < 10 ; i++) { //This for loop can be your data set
Row row = sheet.createRow(rowNumber++);
int columnNumber = 0; //Cell or Column number starting with 0
for (j = 0 ; j < 5 ; j++) { //This for loop can be your data set
Cell cell = row.createCell(columnNumber++);
cell.setCellValue("Some string value");
}
}
I am reading an Excel file and writing the content into an already existing file based on sheet name. The Excel file has 3 header columns.
XSSFSheet conSheet = workbook.getSheet("EMPLOYYEE");
XSSFRow headerRow = conSheet.getRow(0);
XSSFRow dataRow = conSheet.createRow(conSheet.getLastRowNum() + 1);
int physicalNumberOfCells = headerRow.getPhysicalNumberOfCells();
for (int i = 0; i < physicalNumberOfCells; i++) {
XSSFCell headerCell = headerRow.getCell(i);
if (headerCell != null) {
String stringCellValue = headerCell.getStringCellValue();
ConvertsColumn charcol = ConvertsColumn.getEnum(stringCellValue);
XSSFCell dataCell = dataRow.createCell(i);
if (charcol != null) {
try {
FileInputStream file = new FileInputStream("file..anme");
Workbook wb1 = new XSSFWorkbook(file);
Sheet sheet1 = wb1.getSheetAt(0);
Iterator < Row > iterator = sheet1.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator < Cell > cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
Cell nextCell = cellIterator.next();
int columnIndex = nextCell.getColumnIndex();
System.out.println(columnIndex + "" + nextCell);
switch (columnIndex) {
case 0:
dataCell.setCellValue(nextCell.getStringCellValue());
break;
case 1:
dataCell.setCellValue(nextCell.getStringCellValue());
break;
case 2:
dataCell.setCellValue(nextCell.getStringCellValue());
break;
default:
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
We are Using POI. When data is writing to the Excel file it is over-writen with the first column and only one column data is adding with one value...
I am not able to read the data for the cell company code and the drop down value for it. I tried reading the data using
try {
Workbook wb = new XSSFWorkbook(new FileInputStream(
"D:/TCA/Test/test.xlsx"));
// org.apache.poi.ss.usermodel.Workbook wb = new XSSFWorkbook(new
// FileInputStream("D:/TCA/Test/aa.xlsx"));
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
Name name = null;
System.out.println(wb.getSheetName(i));
for (Row row : sheet) {
name = sheet.getWorkbook().createName();
// System.out.println("rownum: " + row.getRowNum());
for (Cell cell : row) {
// System.out.println(cell);
handleCell(cell.getCellType(), cell);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I wants to open xlsx files stored in a folder (one by one) and copy that sheet data column by column (if column name matches) to another file stored in other folder.
Column name mapping data is stored in a sheet.
Suppose sheet 1 contains column name mapping. using this mapping, I want to copy data of each column from each sheet stored in a particular folder to another file stored in another folder.
I tried with this code given below, but I am able to read and write compare headers, but I am unable to read from file one by one.
Code:
public class Read {
public static void main(String[] args) throws IOException{
//Create blank workbook
HSSFWorkbook workbook1 = new HSSFWorkbook();
HSSFSheet spreadsheet = workbook1.createSheet(" Info ");
//Create row object
// HSSFRow row1;
ArrayList<String> lst = new ArrayList<String>();
Read read = new Read();
String x ="Name";
//int columnIndex = 0;
lst = read.extractExcelContentByColumnIndex(x);
//int rowid = 0;
//row1 = spreadsheet.createRow(rowid++);
//Object [] objectArr = empinfo.get(key);
//int cellid = 0;
//int i=0;
for(int RowNum=0; RowNum<lst.size();RowNum++){
HSSFRow row1 = spreadsheet.createRow(RowNum);
for(int ColNum=0; ColNum<1;ColNum++){
HSSFCell cell = row1.createCell(ColNum);
cell.setCellValue(lst.get(RowNum).toString());
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("Writesheet.xls"));
// System.out.println(lst);
workbook1.write(out);
out.close();
}
public ArrayList<String> extractExcelContentByColumnIndex( String colName)
{
ArrayList<String> columndata = null;
int columnIndex= 0;
int flag=0;
try {
File f = new File("abc.xlsx");
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<String>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell1 = cellIterator.next();
String temp=cell1.getStringCellValue().toString();
//System.out.println(temp);
if(temp.equals(colName)){
columnIndex=cell1.getColumnIndex();
flag=1;
break;
}
}
if(flag==1)
{
flag = 0;
break;
}
}
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// System.out.println(row.getRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){
//To filter column headings
if(cell.getColumnIndex() == columnIndex){
// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(colName);
for(String ele : columndata){
System.out.println(ele);
}
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
}
For reading files one by one you can use java.io.File.listFiles() method.
The method returns the array of abstract pathnames defining the
files in the directory denoted by this abstract pathname.
Sample code
File folder = new File(path / up / to / folder);
File[] listOfFiles = folder.listFiles();
for (File file: listOfFiles) {
if (file.isFile() && file.getName().contains(".xlsx")) {
// if you want to read only xlsx files
// Your logic
}
}