Using the first method i am writing the query results to xls file and using second i am uploading to destination DB. It works fine with the Excel files created by the first method. If i edit any created excel file it fails to read some cells and throws error. Any body faced this issue. Any solution or suggesion.
TIA
public void exportData(Map<String, String> queries,Connection conn) {
Connection connection=conn;
try{
List<String> list1=new ArrayList<String>(queries.keySet());
for(int j=0;list1.size()>j;j++){
Workbook book1=new HSSFWorkbook();
Sheet Sheet1= book1.createSheet("sheet1");
PreparedStatement preparedStatement = connection.prepareStatement(queries.get(list1.get(j)));
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData rsmd=resultSet.getMetaData();
boolean isDataAvail = resultSet.next();
if(isDataAvail){
Row headerRow = Sheet1.createRow(0);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
Cell cell1 = headerRow.createCell(i-1);
cell1.setCellValue(rsmd.getColumnName(i));
}
int row=1;
do {
Row row1 = Sheet1.createRow(row);
for (int i = 1; i <=rsmd.getColumnCount(); i++) {
Cell cell2 = row1.createCell(i-1);
String s=rsmd.getColumnTypeName(i);
if(s.equalsIgnoreCase("NUMBER")){
if(resultSet.getString(i)==null)
cell2.setAsActiveCell();
else{
cell2.setCellValue(resultSet.getDouble(i));
}
}else if(s.equalsIgnoreCase("VARCHAR2")||s.equalsIgnoreCase("VARCHAR")){
if(resultSet.getString(i)==null)
cell2.setAsActiveCell();
else
cell2.setCellValue(resultSet.getString(i));
}else if(s.equalsIgnoreCase("DATE")){
if(resultSet.getDate(i)==null)
cell2.setAsActiveCell();
else{
cell2.setCellValue((Date)resultSet.getTimestamp(i));
CellStyle style = book1.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
cell2.setCellStyle(style);
}
}else{
cell2.setCellValue(resultSet.getString(i));
}
} row++;
}while (resultSet.next());
String fname1=folder+list1.get(j)+".xls";
FileOutputStream output;
output=new FileOutputStream(new File(fname1));
book1.write(output);
output.close();
listOfDataTables.add(list1.get(j));
fileNum++;
query++;
logger.info("F.no."+fileNum+"."+list1.get(j)+"--File created successfully");
}
else{
query++;
logger.info("No data found for table"+"("+query+") :"+list1.get(j));
}
resultSet.close();
}
}
catch (Exception exception) {
logger.info("*****ERROR*****"+exception);
logger.log(Level.SEVERE, exception.getMessage(), exception);
exception.getLocalizedMessage();
exception.printStackTrace();
status="ERROR";
}
finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
logger.info("*****ERROR*****"+e);
e.printStackTrace();
}
}
}
}
public int dataTransfer(String fileName,Connection connection) {
int no=0;
String fName=folder+fileName+".xls";
try {
Statement preparedStatement =connection.createStatement();
FileInputStream inputFile = new FileInputStream(fName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(inputFile);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
String insertQuery="";
String columnQuery="";
if(rowIterator.hasNext()){
columnQuery="insert into "+fileName+"(";
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
columnQuery=columnQuery+cell.getStringCellValue()+",";
no++;
}
columnQuery=columnQuery.substring(0, columnQuery.length()-1);
columnQuery=columnQuery+") values (";
}
int rowCounter=0;
int set=0;
while (rowIterator.hasNext() && set<=no)
{
insertQuery=columnQuery;
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(cell)){
double temp=cell.getNumericCellValue();
Date date = HSSFDateUtil.getJavaDate(temp);
String dateFmt = cell.getCellStyle().getDataFormatString();
String strValue = new CellDateFormatter(dateFmt).format(date);
strValue="to_date("+"'"+strValue+"'"+",'mm/dd/yyyy hh24:mi')";
insertQuery=insertQuery+strValue+",";
}else{
insertQuery=insertQuery+cell.getNumericCellValue()+",";
}
}
else if(cell.getCellType()==Cell.CELL_TYPE_STRING)
insertQuery=insertQuery+"'"+cell.getStringCellValue()+"',";
else if(cell.getCellType()==2){
insertQuery=insertQuery+cell.getDateCellValue()+",";
}
else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
insertQuery=insertQuery+"null,";
}
insertQuery=insertQuery.substring(0, insertQuery.length()-1);
insertQuery=insertQuery+")";
preparedStatement.addBatch(insertQuery);System.out.println(insertQuery);
rowCounter++;
}
preparedStatement.executeBatch();
inputFile.close();
listOfProcessedTables.add(fileName);
preparedStatement.close();
return rowCounter;
}
catch (Exception exception) {
logger.info("*****ERROR*****"+exception);
exception.printStackTrace();
logger.log(Level.SEVERE, exception.getMessage(), exception);
StatusCount++;
return 0;
}
}
Related
Here is an example of what i could like to do:
Is there a way to output all the cells between startprint and end_print, i've got like 3 sheet in excel with same place holder, and i want to view only the data between startprint and endprint, for now all i can do is print out all the 3 sheet with all the content, here is my code:
public class ReadInvoices {
private static final String NAME = "C:\\Users\\........\\excelfile.xlsx";
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File(NAME));
Workbook workbook = new XSSFWorkbook(file);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Sheet> sheets = workbook.sheetIterator();
while(sheets.hasNext()) {
Sheet sh = sheets.next();
System.out.println("Sheet name is "+sh.getSheetName());
System.out.println("---------");
Iterator<Row> iterator = sh.iterator();
while(iterator.hasNext()) {
Row row = iterator.next();
Iterator<Cell> cellIterator = row.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue+"\t");
}
System.out.println();
}
}
workbook.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
I don't have a spreadsheet to test this code.
The processLines method tests for the start print row and the end print row. When we're in between the start print and end print rows, we print the rows.
I'm not sure if this line is correct. I'm trying to get the cell from column A.
String text = row.getColumnObject(0);
Edit: Maybe this will work.
Iterator<Cell> cellIterator = row.iterator();
Cell cell = cellIterator.next();
String text = dataFormatter.formatCellValue(cell);
Here's the example code.
public class ReadInvoices {
private static final String NAME = "C:\\Users\\.......\excelfilename.xlsx";
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File(NAME));
Workbook workbook = new XSSFWorkbook(file);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Sheet> sheets = workbook.sheetIterator();
while (sheets.hasNext()) {
Sheet sh = sheets.next();
System.out.println("Sheet name is " + sh.getSheetName());
System.out.println("---------");
processLines(dataFormatter, sh);
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void processLines(DataFormatter dataFormatter, Sheet sh) {
boolean printLine = false;
Iterator<Row> iterator = sh.iterator();
while (iterator.hasNext()) {
Row row = iterator.next();
Iterator<Cell> cellIterator = row.iterator();
Cell cell = cellIterator.next();
String text = dataFormatter.formatCellValue(cell);
if (printLine && text.equals("End_print")) {
printLine = false;
}
if (printLine) {
printRow(dataFormatter, row);
}
if (!printLine && text.equals("StartPrint")) {
printLine = true;
}
}
}
private static void printRow(DataFormatter dataFormatter, Row row) {
Iterator<Cell> cellIterator = row.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
System.out.println();
}
}
I am coding a program to format the contents of an excel file. Eclipse is saying that the line Cell cell = cellIterator.next(); is unreachable and I don't understand why. Where did I go wrong?
private String formatExcel(File excel)
{
this.statusLabel.setText("formatting...");
try
{
FileInputStream file = new FileInputStream(excel);
try
{
this.workbook = WorkbookFactory.create(file);
}
catch (InvalidFormatException ex)
{
file.close();
}
int excelType = 0;
if ((this.workbook instanceof HSSFWorkbook)) {
excelType = 1;
}
int sheetNum = 0;
try
{
sheetNum = Integer.parseInt(this.sheetNumber.getText());
}
catch (NumberFormatException e)
{
file.close();
}
if ((sheetNum < 1) || (sheetNum > this.workbook.getNumberOfSheets()))
{
file.close();
return "Please input a valid sheet number.";
}
Sheet sheet = this.workbook.getSheetAt(sheetNum - 1);
sheet.setZoom(17, 20);
Iterator<Row> rowIterator = sheet.iterator();
int startRow = Integer.MAX_VALUE;
Iterator<Cell> cellIterator;
for (; rowIterator.hasNext(); cellIterator.hasNext())
{
Row row = (Row)rowIterator.next();
cellIterator = row.cellIterator();
continue;
Cell cell = (Cell)cellIterator.next(); // <- this line is unreachable
switch (cell.getCellType())
{
case 4:
break;
case 0:
break;
case 1:
if (cell.getStringCellValue().trim().equalsIgnoreCase("Condition Code")) {
startRow = cell.getRowIndex();
}
if ((cell.getRowIndex() > startRow + 1) && (cell.getColumnIndex() > 0) && (cell.getColumnIndex() < 5)) {
if (excelType == 0) {
cell.setCellValue(formatCellXSSF(
cell.getStringCellValue(),
cell.getColumnIndex()));
} else {
cell.setCellValue(formatCellHSSF(
cell.getStringCellValue(),
cell.getColumnIndex()));
}
}
if (!cell.getStringCellValue().trim().equalsIgnoreCase("<<Test Data>>")) {
if (!cell.getStringCellValue().trim().equalsIgnoreCase("<<Screenshots>>")) {
break;
}
}
break;
}
}
sheet.autoSizeColumn(5);
file.close();
FileOutputStream out = new FileOutputStream(excel);
this.workbook.write(out);
out.close();
return "";
}
catch (FileNotFoundException ex)
{
return "Error. File is open. Please close it first.";
}
catch (IOException ex) {}
return "Cannot format file because it is open. Please close it first.";
}
You have an unconditionnal continue in your for loop. Next statements are never executed, no way.
for (; rowIterator.hasNext(); cellIterator.hasNext())
{
Row row = (Row)rowIterator.next();
cellIterator = row.cellIterator();
continue;
Cell cell = (Cell)cellIterator.next();
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 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();
}
Following is the code to print the sum of the cells in the same row in a loop. When I run, the first loop works fine and I get the value of the sum but during the second loop, it throws the null pointer exception at line double z= cell.getNumericCellValue(); after printing the value of z.
try{
FileInputStream file = new FileInputStream("C:/Documents and Settings/m.y/My Documents/test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
// HSSFCell cell = null;
Row r = sheet.getRow(0);
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
double summ=1.0;
for(int i =1 ; i<=sheet.getLastRowNum(); i++){
for(int j=1; j<r.getLastCellNum();j++)
{
cell = sheet.getRow(i).getCell(j);
// if(HSSFCell.CELL_TYPE_NUMERIC==cell.getCellType())
// {
double z= cell.getNumericCellValue();
System.out.println(z);
summ=summ+z;
// }
}
System.out.println(summ);
Cell mycell1=r.createCell(3);
mycell1.setCellValue(summ);
summ=0.0;
}
file.close();
FileOutputStream outFile =new FileOutputStream("C:/Documents and Settings/m.y/My Documents/test.xls");
workbook.write(outFile);
outFile.close();
}catch (IOException e) {
e.printStackTrace();
}
}
Note: The excel file can be like:
Name sub1 Sub2
m 2 3
n 5 6
j 4 9
try this
try{
FileInputStream file = null;
try {
file = new FileInputStream("C:/Documents and Settings/m.y/My Documents/test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
double summ = 1.0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
int i = 0;
double z = 0.0;
while (cellIterator.hasNext()) {
cell = sheet.getRow(i).getCell(j);
if (i == 0) {
System.out.println(cell.getStringCellValue());
} else {
z = cell.getNumericCellValue();
}
System.out.println(z);
summ = summ + z;
i++;
// }
}
System.out.println(summ);
Cell mycell1 = r.createCell(3);
mycell1.setCellValue(summ);
summ = 0.0;
}
file.close();
FileOutputStream outFile = new FileOutputStream("C:/Documents and Settings/m.y/My Documents/test.xls");
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
file.close();
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}