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);
Related
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'm having a hard time visualizing a good way to perform this. As you can see by the below code, I'm going through every row and getting values for each cell. However, when actually running the query to add them to a table, it's easier if you can input a whole row at a time. There's enough columns/variability though where I don't want to make a separate value for each column in the excel document. Any ideas on how to run this more efficiently?
for (int i=1; i<rowNum; i++) {
XSSFRow row = ws.getRow(i) ;
for (int j = 0; j<colNum; j++) {
XSSFCell cell = row.getCell(j) ;
String value = cell.getStringCellValue();
data[i][j] = value ;
System.out.println("the value is " + value);
stmt.executeUpdate("INSERT INTO databasetable VALUES(" + value + ")");
}
}
You can spawn an iterator on your worksheet to have it more efficient.
Something like the below
public static Vector read(String fileName) {
Vector cellVectorHolder = new Vector();
try{
FileInputStream myInput = new FileInputStream(fileName);
XSSFWorkbook myWorkBook = new XSSFWorkbook(myInput);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
XSSFRow myRow = (XSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
List list = new ArrayList();
while(cellIter.hasNext()){
XSSFCell myCell = (XSSFCell) cellIter.next();
list.add(myCell);
}
cellVectorHolder.addElement(list);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
I ended up using concentation and just inserted a , between each value in the for loop.
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"));
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();
}