I have a List<String> that has few elements and I want to write these elements into an Excel sheet using Apache POI. Also I want to put the data into separate rows after each 10 items. For example, my list has following elements :
["aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","jjj","kkk","lll","mmm","nnn","ooo","ppp","qqq","rrr","sss","ttt",....]
I want this in excel sheet in following format
col1, col2, col3, col4, col5, col6, col7, col8, col9, col10
row1 : aaa, bbb, ccc, ddd, eee, fff, ggg, hhh, iii, jjj
row2 : kkk, lll, mmm, nnn, ooo, ppp, qqq, rrr, sss, ttt
Can this be achieved through Apache POI?
I have tried the following (I am really bad in loops)
public void csvUpdateWorksheet1(String fileName, String sheetName, List<String> data) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(sheetName);
logger.info(data.size());
int rownum = 0;
for (int i = 0; i < data.size(); i++) {
Row row = sheet.createRow(i);
Cell cell = row.createCell(i);
cell.setCellValue(data.get(i));
}
csvWriteToFile(workbook, fileName);
}
You will need to create the next row once you have created 10 cells in the current row.
int r = 0;
int c = 0;
int maxCellsPerRow = 10;
Row row = sheet.createRow(r);
for (String str : data)
{
Cell cell = row.createCell(c);
cell.setCellValue(str);
c++;
// Create and advance to next row if needed.
if (c >= maxCellsPerRow)
{
c = 0;
r++;
row = sheet.createRow(r);
}
}
int rownum = 0;
int colnum = 0;
int itemsPerRow = 20;
String outfilename = "test.xls";
List<String> values = new ArrayList<String>();
// add some values ...
HSSFWorkbook book = new HSSFWorkbook();
HSSFSheet sheet = book.createSheet(
HSSFRow row = sheet.getRow(rownuw);
for(String s : values) {
HSSFCell cell = row.createCell(colnum);
cell.setCellValue(Integer.parseInt(id));
colnum = (column+1)%itemsPerRow;
if(colnum == 0) {
rownum++;
row = sheet.getRow(rownuw);
}
}
File f = new File("src/main/resources/films.xls");
FileOutputStream fos = new FileOutputStream(f);
book.write(fos);
fos.flush();
fos.close();
Related
I can read the data of one col 0 by using below code. I need to fetch the record for duplicate value present in col 0
FileInputStream fis = new FileInputStream(theNewestFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
String cellValueMaybeNull;
List<Cell> cells = new ArrayList<Cell>();
for (int rowIndex = 0; rowIndex <= spreadsheet.getLastRowNum(); rowIndex++) {
row = (XSSFRow) spreadsheet.getRow(rowIndex);
if (row != null) {
int colIndex = 0;
Cell cell = row.getCell(colIndex);
if (cell != null) {
// Found column and there is value in the cell.
cellValueMaybeNull = cell.getStringCellValue();
// Do something with the cellValueMaybeNull here ...
System.out.println(cellValueMaybeNull);
}
}
}
Declare a Map and capture all the duplicates and print it later. If the list size is more than 1 then it is duplicate case scenario.
FileInputStream fis = new FileInputStream(theNewestFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
String cellValueMaybeNull;
List<Cell> cells = new ArrayList<Cell>();
Map<String,List<String>> duplicateCheck = new HashMap<String,List<String>>();
for (int rowIndex = 0; rowIndex <= spreadsheet.getLastRowNum(); rowIndex++) {
row = (XSSFRow) spreadsheet.getRow(rowIndex);
if (row != null) {
int colIndex = 0;
Cell cell = row.getCell(colIndex);
if (cell != null) {
// Found column and there is value in the cell.
cellValueMaybeNull = cell.getStringCellValue();
// Do something with the cellValueMaybeNull here ...
if(duplicateCheck.get(cellValueMaybeNull) != null) {
duplicateCheck.get(cellValueMaybeNull).add(cellValueMaybeNull);
}
else {
List<String> list = new ArrayList<String>();
list.add(cellValueMaybeNull);
duplicateCheck.put(cellValueMaybeNull, list);
}
}
}
}
for(List<String> duplicateValue : duplicateCheck.values()) {
if(duplicateValue.size() > 1) {
System.out.println("Duplicate values :"+duplicateValue);
}
}
Cannot iterate the full extent of rows in my XLS spreadsheet. The code {sheet.getPhysicalNumberOfRows} returns 33492 without raising exception, but there are about 43,000 rows??.
If I supply the right number manually the loop executes without complaint.
It must be simple answer but I cannot find one anywhere. can somebody help?
try {
POIFSFileSystem fs = new POIFSFileSystem(new
FileInputStream(fileLocation));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows(); //Gets => 33494
int cols = 1; // No of columns
int tmp = 0;
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if (row != null) {
cell = row.getCell(0);
if (cell != null) {
System.out.println("Line number: " + r " = " + cell);
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
I am inserting a list of numbers into a column in Excel (column A) with Java. the following column has a list of average numbers (Column B). Column C has a list of formulas like this: =IF(B1 < 1,0,((A1)-B1)/B1).
In my program, I want to have the formulas in column C re-evaluate after I've input the new data so then I can extract the new cell value into Java. I'm checking to see if any new result in column C is -1.0.
I've tried to use FormulaEvaluator before extracting column C values but I still get the old values. I've also tried writing and closing the workbook and opening it again but that also hasn't worked.
//Pull the values stored procedure
ResultSet rs = dbutils.sqlserverdbvaliation(query, db);
System.out.println("Returned the Result Set");
//Get number of rows in result row to set array size
rs.last();
arraySize = rs.getRow();
rs.beforeFirst();
//Store values from resultSet into an array
int[] dlArray = new int[arraySize];
while(rs.next()) {
//Activity Process Count is name of ResultSet Column
dlArray[count] = rs.getInt("ActivityProcessCount");
count++;
}
//Create workbook
InputStream inp = new FileInputStream("C:\\TestWorkbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(1);
FormulaEvaluator evaluator =
wb.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateAll();
System.out.println(Arrays.toString(dlArray));
//Write the values from the array to the spreadsheet
int excelCount = 1;
for (int i = 0; i < arraySize ; i++) {
Row row = sheet.getRow(excelCount);
Cell cell = row.getCell(2);
cell.setCellValue(dlArray[i]);
evaluator.evaluateAll();
excelCount++;
}
FileOutputStream fos = new FileOutputStream("C:\\TestWorkbook.xlsx");
evaluator.evaluateAll();
wb.write(fos);
wb.close();
InputStream inp2 = new FileInputStream("C:\\TestWorkbook.xlsx");
Workbook wb2 = WorkbookFactory.create(inp2);
org.apache.poi.ss.usermodel.Sheet sheet2 = wb2.getSheetAt(1);
excelCount = 1;
for (int i = 0; i < arraySize ; i++) {
Row row = sheet2.getRow(excelCount);
Cell cell = row.getCell(4);
if (cell.getNumericCellValue() == -1.0) {
ExcelUtils.setCellStyle(excelPath, sheetName, excelCount, 5,
YELLOW);
}
else {
ExcelUtils.setCellStyle(excelPath, sheetName, excelCount, 5,
GREEN);
}
excelCount++;
}
1) I am trying to read the values from the webtable of an appliation and write it into the excel sheet one by one.
2) There are 4 values in each row of the webtable that need to be written to excel sheet, but there are some images in each row that i'm ignoring bu using below code.
text.length()>2
.
3) There will be 200-300 rows in webtable that need to be fetched and written to excel sheet.
This is the code i have tried. But i dont know how to write it into each row of the excel sheet one by one. Please help me in this regard.
//get the table
WebElement statusTable = browser.findElement(By.id("projectstatus"));
//Get all the rows in the table
List<WebElement> allRows = statusTable.findElements(By.tagName("tr"));
//Get the size(row no) of allRows
int rowSize = allRows.size();
System.out.println(rowSize);
for (WebElement row : allRows) {
//Get all cell values in each row
List<WebElement> allCells = row.findElements(By.tagName("td"));
//System.out.println(allCells.size());
if(allCells.size() > 1){
for (WebElement cell : allCells) {
String text = cell.getText();
if(text.length()>2){
String value = cell.getText();
}
}
}
// locate the test xl file
File file = new File("e:\\Testing_emi.xls");
// create input stream
FileInputStream fis = new FileInputStream(file);
// create workbook
HSSFWorkbook wb = new HSSFWorkbook(fis);
// get sheet
HSSFSheet sheet1 = wb.getSheet("Sheet1");
// get rows
HSSFRow row = sheet1.getRow(1);
HSSFCell cellEx = row.getCell(0);
if (cellEx == null) {
cellEx = row.createCell(0);
}
cellEx.setCellValue(value);
//get the table
WebElement statusTable = browser.findElement(By.id("projectstatus"));
//Get all the rows in the table
List<WebElement> allRows = statusTable.findElements(By.tagName("tr"));
//Get the size(row no) of allRows
int rowSize = allRows.size();
System.out.println(rowSize);
// locate the test xls file
File file = new File("e:\\Testing_emi.xls");
// create input stream
FileInputStream fis = new FileInputStream(file);
// create workbook
HSSFWorkbook wb = new HSSFWorkbook(fis);
// get sheet
HSSFSheet sheet1 = wb.getSheet("Sheet1");
// get rows
HSSFRow row;
for (int i=0; i<rowSize; i++)
{
WebElement webRow = allRows.get(i);
//Get all cell values in each row
List<WebElement> allCells = webRow.findElements(By.tagName("td"));
//System.out.println(allCells.size());
if(allCells.size() > 1)
{
HSSFRow excelRow = sheet1.createRow(i);
for (int j=0; j<allCells.size(); j++)
{
WebElement webCell = allCells.get(j);
String text = webCell.getText();
if(text.length()>2)
{
Cell excelCell = excelRow.createCell();
excelCell.setValue(webCell.getText());
}
}
}
}
sheet1.close();
Read the values from the Web Table of an application and write it in to the excel sheet one by one.There are 5 values in each row of the Web Table and that need to written in Excel sheet. Below is the working code.
System.setProperty("webdriver.chrome.driver","C:\\Users\\Documents\\Selenium jars\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://cosmocode.io/automation-practice-webtable/");
WebElement table = driver.findElement(By.xpath("//*[#id='countries']/tbody"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
int rowcount = rows.size();
FileOutputStream fis = new FileOutputStream(new File("C:\\Users\\Documents\\Selenium\\output.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = wb.createSheet("First Sheet");
for (int row = 0; row < rowcount; row++) {
List<WebElement> columns_inrow = rows.get(row).findElements(By.tagName("td"));
int columns_count = columns_inrow.size();
System.out.println("Number of cells in Row " + row + " are " + columns_count);
Row ro = sh.createRow(row);
for (int column = 0; column < columns_count; column++) {
String celltext = columns_inrow.get(column).getText();
System.out.println(
"Cell Value of row number " + row + " and column number " + column + " Is " + celltext);
ro.createCell(column).setCellValue(celltext);
}
System.out.println("===========================");
}
wb.write(fis);
wb.close();
}
When i am creating multiple sheets using Apache poi and servlets. It is creating the sheet but not writing the data to file. I am trying to write the first 1000 records to sheet1 and next 1000 to sheet2 through below code, but not working
private void writeDataToExcelFile(String string,
ArrayList<ArrayList<String>> excelData, OutputStream outputStream) {
HSSFWorkbook myWorkBook = new HSSFWorkbook();
String sheetName = "";
sheetName = "Document-" + 0;
HSSFSheet mySheet = myWorkBook.createSheet();
HSSFRow myRow = null;
HSSFCell myCell = null;
for (int rowNum = 0; rowNum < excelData.size(); rowNum++) {
ArrayList<String> rowData = excelData.get(rowNum);
if(rowNum>0 && rowNum%1000 == 0)
{
sheetName = "Document-" + (rowNum/1000);
mySheet = myWorkBook.createSheet();
}
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < rowData.size(); cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(rowData.get(cellNum));
}
}
System.out.println("Last row:" + mySheet.getLastRowNum());
System.out.println("Row number:" + mySheet.rowIterator().next().getRowNum());
try {
myWorkBook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What is wrong with my logic.Please do the needful help.
Thanks
When you loop through the dataset, you are wanting to split at row 1000 to start a new sheet, which is fine, however when you start the new sheet, the next row you create is row 1001 (the outer loop index variable)
myRow = mySheet.createRow(rowNum);
To get the effect you wish, change the loop to be something like this:
int currentRow = 0;
for (int rowNum = 0; rowNum < excelData.size(); rowNum++)
{
ArrayList<String> rowData = excelData.get(rowNum);
if(currentRow == 1000)
{
sheetName = "Document-" + (rowNum/1000);
mySheet = myWorkBook.createSheet();
currentRow = 0;
}
myRow = mySheet.createRow(currentRow);
for (int cellNum = 0; cellNum < rowData.size(); cellNum++)
{
myCell = myRow.createCell(cellNum);
myCell.setCellValue(rowData.get(cellNum));
}
currentRow++;
}
I haven't compiled this, so I don't know if it'll work right away, but it should point you in the right direction.
HTH
Edit
Thinking about this further, you could get the same effect from making a 1 line change to the original application (albeit losing a little bit of clarity):
myRow = mySheet.createRow(rowNum%1000);