My code imports the excel file then put a certain column in to a textarea
I want to know how would i modify the excel file if for example i edited something on the textarea that edit should be saved on the excel file
String excelFilePath = "sample.xlsx";
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(excelFilePath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
Workbook workbook = null;
try {
workbook = new XSSFWorkbook(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
}
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
Iterator<Cell> scellIterator = nextRow.cellIterator();
cellIterator.next();
scellIterator.next();
scellIterator.next();
Cell topicsCell = cellIterator.next();
Cell topicSentimentCell =scellIterator.next();
String cellContents = topicsCell.getStringCellValue();
String scellContents = topicSentimentCell.getStringCellValue();
String[] topics = cellContents.split(";");
String[] topicSentiment = scellContents.split(";");
ArrayList<String> tpc = new ArrayList<>();
ArrayList<String> topicsents = new ArrayList<>();
for(int i = 0; i < topics.length; i++) {
topics[i] = topics[i].trim();
tpc.add(topics[i]);
for (int indx = 0; indx < tpc.size(); indx++) {
textArea.append(tpc.get(indx)+"\n");
}
}
for(int si = 0; si < topicSentiment.length; si++) {
topicSentiment[si] = topicSentiment[si].trim();
topicsents.add(topicSentiment[si]);
for (int index = 0; index < topicsents.size(); index++) {
// textArea.append(topicsents.get(index)+"\n");
System.out.print(topicsents+"\n");
}
}
}
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
Open a file as XSSFWorkbook
Open a XSSFSheet of the workbook
Make some changes in the sheet. For example change the value of a XSSFCell
Save the changes by workbook.write()
Example
// Open workbook and sheet
final XSSFWorkbook workbook = new XSSFWorkbook(new File("filename.xlsx"));
final XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate rows
final int firstRowNumber = sheet.getFirstRowNum();
final int lastRowNumber = sheet.getLastRowNum();
for (int rowNumber = firstRowNumber; rowNumber < lastRowNumber; rowNumber++ ) {
final XSSFRow row = sheet.getRow(rowNumber);
if (row == null) continue;
// Iterate columns
final int firstColumnNumber = row.getFirstCellNum();
final int lastColumnNumber = row.getLastCellNum();
for (int columnNumber = firstColumnNumber; columnNumber < lastColumnNumber; columnNumber++ ) {
final XSSFCell cell = row.getCell(firstColumnNumber);
if (cell == null) continue;
// Make some changes
cell.setCellValue("new Value");
}
}
// Save changes
workbook.write(new FileOutputStream("newFilename.xlsx"));
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);
}
}
i have an excel file with 3 columns. i already store the "B" columns to array list and check it if the value is duplicate or not. now i have problem to write the "Duplicate" value to "C" columns. how to write on specific columns?
here is my code
FileInputStream file = new FileInputStream(new File(
"file name"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
ArrayList<String> col = new ArrayList<String>();
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(cell.getColumnIndex()==1) {
col.add(cell.getStringCellValue());
System.out.print(cell.toString());
}
}
System.out.println();
}
for(int a = 0; a < 14; a++) {
if(col.get(a).equals("Order ID")) {
if(col.get(a).equals(col.get(a+1))) {
System.out.println("ROW no "+a+"Double Order");
}
} else {
if(col.get(a).equals(col.get(a+1)) || col.get(a).equals(col.get(a-1))) {
if(col.get(a).trim().length()>0) {
System.out.println("ROW no "+a+"Double Order");
col.add("Double");
}
}
}
}
FileOutputStream fileOut = new FileOutputStream("file name");
workbook.write(fileOut);
fileOut.close();
You do not need to iterate twice to identify and write against duplicate rows separately. You can do it like following:
private static void identifyDuplicateOrders() throws IOException {
FileInputStream file = new FileInputStream(new File("D:\\home\\test_in.xlsx"));
final FileOutputStream fileOut = new FileOutputStream("D:\\home\\test_out.xlsx");
XSSFWorkbook workbook = null;
try {
workbook = new XSSFWorkbook(file);
final XSSFSheet sheet = workbook.getSheetAt(0);
final Iterator<Row> rowIterator = sheet.iterator();
final Set<String> orderIds = new HashSet<String>();
while (rowIterator.hasNext()) {
final Row row = rowIterator.next();
final int rowNumber = row.getRowNum();
// SKIP HEADER
if (rowNumber == 0) {
continue;
}
System.out.print("Row " + rowNumber);
// GET ORDER ID CELL
final Cell cell = row.getCell(1);
if (!orderIds.add(cell.getStringCellValue())) {
// CREATE DOUBLE ORDER CELL
row.createCell(2).setCellValue("Duplicate");
System.out.println(" " + cell.toString() + " is Duplicate.");
} else {
System.out.println(" Order is Unique");
}
}
workbook.write(fileOut);
} finally {
workbook.close();
file.close();
fileOut.close();
}
}
You can write the word Duplicate in a loop iterating rows, you don't need to hold array of values. To check duplicates you can use Set and check if add returns false.
e.g.
public static void main(String... args) throws IOException {
try (FileInputStream file = new FileInputStream(new File(args[0]));
XSSFWorkbook workbook = new XSSFWorkbook(file)) {
Set<String> orders = new HashSet<>(20);
XSSFSheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
// skip header if needed
if (row.getRowNum() == 0) {
continue;
}
// 1 for OrderId as in example
Cell orderCell = row.getCell(1);
if (!orders.add(getValue(orderCell))) {
Cell infoCell = row.getCell(2);
if (infoCell == null) {
infoCell = row.createCell(2);
}
infoCell.setCellValue("Duplicate");
}
}
// write result in new file
workbook.write(new FileOutputStream(new File(args[0] + ".result.xlsx")));
}
}
private static String getValue(Cell orderCell) {
switch (orderCell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
return Double.toString(orderCell.getNumericCellValue());
case Cell.CELL_TYPE_STRING:
return orderCell.getStringCellValue();
}
return null;
}
The output file is created but only the first cell is written and nothing else. I tested it with system print and all the data that I want shows up in console but is not written to the worksheet.
public class excel_read_2 {
public static void main(String[] args)
{
try
{
FileInputStream file = new FileInputStream(new File("C:/Users/h.M/Desktop/20151007-110016_outgoing.xls")); //input
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
FileOutputStream fileOut = new FileOutputStream("C:/Users/h.M/Desktop/workbook.xls"); //output
int rowcounter = 0;
for (int rowNum = 150; rowNum < 180; rowNum++) {
Row r = sheet.getRow(rowNum);
if (r == null) {
continue;
}
int lastColumn=6;
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null){
}
else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
Row row = sheet1.createRow((short)rowcounter);
Cell cell = row.createCell(cn);
row.createCell(cn).setCellValue(c.getStringCellValue());
System.out.println("The cell was a string \" " + c.getStringCellValue()+" \" ");
} else if (c.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
Row row = sheet1.createRow((short)rowcounter);
Cell cell = row.createCell(cn);
row.createCell(cn).setCellValue(c.getNumericCellValue());
System.out.println("The cell was a number " + c.getNumericCellValue());
}
}
rowcounter++;
}
wb.write(fileOut);
fileOut.close();
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Create the new row before you loop, then use it once per loop.
Row row = sheet1.createRow((short)rowcounter);
int lastColumn=6;
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null){
}
else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
Cell cell = row.createCell(cn);
cell.setCellValue(c.getStringCellValue());
I have a following code that reads logins and passwords from xls file starting from the second row(it skips column names) and writes it into a 2d array. But it only works if the sheet doesn't have blank cells in any of the rows. What should i do to make it work with empty cells?
private static Object[][] getUsersFromXls(String sheetName) {
final File excelFile = new File("src//resources//TestData.xls");
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(excelFile);
workbook = new HSSFWorkbook(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
sheet = workbook.getSheet(sheetName);
final int numberOfRows = sheet.getLastRowNum();
final int numberOfColumns = sheet.getRow(0).getLastCellNum();
final String[][] xlsData = new String[numberOfRows][numberOfColumns];
String cellValue;
for (int i = 1; i <= numberOfRows; i++) {
final HSSFRow row = sheet.getRow(i);
for (int j = 0; j < numberOfColumns; j++) {
final HSSFCell cell = row.getCell(j);
final int cellType = cell.getCellType();
if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
throw new RuntimeException("Cannot process a formula. Please change field to result of formula.");
} else {
cellValue = String.valueOf(cell);
xlsData[i - 1][j] = cellValue;
}
}
}
return xlsData;
}
I am facing a problem while iterating all the cells in a row, I am able to read first 4 cells properly rest all coming as null. Any help appreciated
//Below is the code I am using
InputStream is = new FileInputStream(new File(fileName));
Workbook workbook = new XSSFWorkbook(is);
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(i);
String name = sheet.getSheetName();
if (name.equals(sheetName)) {
Iterator<Row> rowItr = sheet.rowIterator();
while (rowItr.hasNext()) {
Row eachRow = rowItr.next();
QuestionObjBuilder builder = new QuestionObjBuilder();
Iterator<Cell> cellItr = eachRow.cellIterator();
int index = 1;
while (cellItr.hasNext()) {
Cell eachCell = cellItr.next();
int cellType = eachCell.getCellType();
String label = "";
if (cellType == Cell.CELL_TYPE_STRING) {
label = eachCell.getStringCellValue();
} else if (cellType == Cell.CELL_TYPE_NUMERIC) {
int value = (int) eachCell.getNumericCellValue();
label = String.valueOf(value);
}
builder = builder.set(index, label);
index++;
if (index > 10) {
break;
}
}
}
}
}
workbook.close();
If your goal is to read all cells from the excel you can use this code,
FileInputStream fileInputStream = new FileInputStream(fileName);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet(sheetName);
Iterator<Row> it = worksheet.rowIterator();
while(it.hasNext()){
HSSFRow r = (HSSFRow) it.next();
Iterator<Cell> it1=r.cellIterator();
while(it1.hasNext()){
HSSFCell cell = (HSSFCell)it1.next();
System.out.println("Row: "+cell.getRowIndex()+" ,Column: "+cell.getColumnIndex());
System.out.println(cell);
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}