STRING cannot be resolved or is not a field - java

ERROR :
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
STRING cannot be resolved or is not a field,NUMERIC cannot be resolved or is not a field,BOOLEAN cannot be resolved or is not a field,BLANK cannot be resolved or is not a field. I am using below code.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public static void main(String[] args) throws Exception {
String filename = "test.xlsx";
try (FileInputStream fis = new FileInputStream(filename)) {
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator<Cell> cells = row.cellIterator();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
org.apache.poi.ss.usermodel.CellType type = cell.getCellTypeEnum();
if (type == CellType.STRING) {
System.out.println("[" + cell.getRowIndex() + ", "
+ cell.getColumnIndex() + "] = STRING; Value = "
+ cell.getRichStringCellValue().toString());
} else if (type == CellType.NUMERIC) {
System.out.println("[" + cell.getRowIndex() + ", "
+ cell.getColumnIndex() + "] = NUMERIC; Value ="
+ cell.getNumericCellValue());
} else if (type == CellType.BOOLEAN) {
System.out.println("[" + cell.getRowIndex() + ", "
+ cell.getColumnIndex() + "] = BOOLEAN; Value ="
+ cell.getBooleanCellValue());
} else if (type == CellType.BLANK) {
System.out.println("[" + cell.getRowIndex() + ", "
+ cell.getColumnIndex() + "] = BLANK CELL");
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Try to import org.apache.poi.ss.usermodel.CellType.
This org.apache.poi.ss.usermodel.CellType type = cell.getCellTypeEnum(); is working but you don't call CellType the same way on next lines.

If you are using the latest version poi-4.0.1 Change all your if condition should simply be :
if (type == STRING) {
// ..............
// ..............
} else if (type == NUMERIC) {
// ..............
// ..............
} else if (type == BOOLEAN) {
// ..............
// ..............
} else if (type == BLANK) {
// ..............
// ..............
}
}

Related

Printing out results in a map loading contents from a xlsx file using POI

so I need to print out the product id and image url from a excel file as I need to modify another file with the contents I retrieve, however for some reason the mappings is empty, but if I print the values out directly it shows them correctly.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class Main {
static final Map<String, String> PRODUCT_CODES_BY_IMAGES = new HashMap<>();
public static void main(String[] args) throws IOException, InvalidFormatException {
File file = new File("./data/stock_met_imageurls.xlsx");
FileInputStream fis = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(fis);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(cell != null && cell.getCellTypeEnum().equals(CellType.STRING)) {
String image_url = null;
String product_id = null;
switch(cell.getColumnIndex()) {
case 0:
image_url = cell.getStringCellValue();
break;
case 2:
product_id = cell.getStringCellValue();
break;
}
if(image_url != null && product_id != null) {
PRODUCT_CODES_BY_IMAGES.put(product_id, image_url);
}
}
}
}
PRODUCT_CODES_BY_IMAGES.forEach((k, v) -> {
System.out.println("key = " + k);
System.out.println("val = " + v);
});
System.out.println("Size = " + PRODUCT_CODES_BY_IMAGES.size());
}
}
if I did under the cases
System.out.println("val = " + cell.getStringCellValue());
it prints it out correctly but for some reason the mappings is empty?
Any help would be greatly appreciated.
Because your map is declared as static final. Check out https://www.baeldung.com/java-final
Fixed, I added the elements in the mappings above the wrong bracket.

How to edit excel file with large data using SXSSF change cell color

I have read all previous ask question but there is solution I found.
How to Edit existing large excel file with SXSSF Streaming api
How to write to an existing file using SXSSF?
I have a existing file which I required to update the content change cell color for some content.
I need to modify excel file with large data over 40,000 rows.
Steps done in below code.
Create new file for Result, Copy file 2 for result to highlight not
equal cell
Create Workbook for 2 compare excel files Temp
XSSFWorkbook XSSF cellStyleRed as SXSSFWorkbook cannot have cellstyle color
keep 100 rows in memory, exceeding rows will be flushed to disk
compareTwoRows from both excel file not equal will change cellstyle color to red on Result file.
Problem is with below code Result file is blank there is no content. I understand my code
is incorrect as SXSSFWorkbook is creating new sheet.
HOW CAN I update result file by change cell color?
package pageobjects;
import java.awt.Color;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.Reporter;
import property.IHomePage;
import utility.SeleniumUtils;
public class Excelcom2try extends SeleniumUtils implements IHomePage {
public static FileOutputStream opstr = null;
XSSFCellStyle cellStyleRed = null;
SXSSFWorkbook sxssfWorkbook = null;
SXSSFSheet sheet = null;
SXSSFRow row3edit = null;
SXSSFCell Cell = null;
#SuppressWarnings("resource")
public void compare() {
try {
// Create new file for Result
XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream fos = new FileOutputStream(new File("\\\\sd\\comparisonfile\\ResultFile.xlsx"));
workbook.write(fos);
workbook.close();
Thread.sleep(2000);
// get input for 2 compare excel files
FileInputStream excellFile1 = new FileInputStream(new File("new File("\\\\sd\\comparisonfile\\UAT_Relationship.xlsx"));
FileInputStream excellFile2 = new FileInputStream(new File(""\\\\sd\\comparisonfile\\Prod_Relationship.xlsx"));
// Copy file 2 for result to highlight not equal cell
FileSystem system = FileSystems.getDefault();
Path original = system.getPath(""\\\\sd\\comparisonfile\\Prod_Relationship.xlsx");
Path target = system.getPath(""\\\\sd\\comparisonfile\\ResultFile.xlsx");
try {
// Throws an exception if the original file is not found.
Files.copy(original, target, StandardCopyOption.REPLACE_EXISTING);
Reporter.log("Successfully Copy File 2 for result to highlight not equal cell");
Add_Log.info("Successfully Copy File 2 for result to highlight not equal cell");
} catch (IOException ex) {
Reporter.log("Unable to Copy File 2 ");
Add_Log.info("Unable to Copy File 2 ");
}
Thread.sleep(2000);
FileInputStream excelledit3 = new FileInputStream(new File("\\\\sd\\comparisonfile\\ResultFile.xlsx"));
// Create Workbook for 2 compare excel files
XSSFWorkbook workbook1 = new XSSFWorkbook(excellFile1);
XSSFWorkbook workbook2 = new XSSFWorkbook(excellFile2);
// Temp workbook
XSSFWorkbook workbook3new = new XSSFWorkbook();
//XSSF cellStyleRed as SXSSFWorkbook cannot have cellstyle color
cellStyleRed = workbook3new.createCellStyle();
cellStyleRed.setFillForegroundColor(IndexedColors.RED.getIndex());
cellStyleRed.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// Get first/desired sheet from the workbook to compare both excel sheets
XSSFSheet sheet1 = workbook1.getSheetAt(0);
XSSFSheet sheet2 = workbook2.getSheetAt(0);
//XSSFWorkbook workbook3new temp convert to SXSSFWorkbook
// keep 100 rows in memory, exceeding rows will be flushed to disk
sxssfWorkbook = new SXSSFWorkbook(100);
sxssfWorkbook.setCompressTempFiles(true);
sheet = sxssfWorkbook.createSheet();
// Compare sheets
if (compareTwoSheets(sheet1, sheet2, sheet)) {
Reporter.log("\\n\\nThe two excel sheets are Equal");
Add_Log.info("\\n\\nThe two excel sheets are Equal");
} else {
Reporter.log("\\n\\nThe two excel sheets are Not Equal");
Add_Log.info("\\n\\nThe two excel sheets are Not Equal");
}
// close files
excellFile1.close();
excellFile2.close();
// excelledit3.close();
opstr.close();
// dispose of temporary files backing this workbook on disk
}catch (Exception e) {
e.printStackTrace();
}
Reporter.log("Successfully Close All files");
Add_Log.info("Successfully Close All files");
}
// Compare Two Sheets
public boolean compareTwoSheets(XSSFSheet sheet1, XSSFSheet sheet2, SXSSFSheet sheet) throws IOException {
int firstRow1 = sheet1.getFirstRowNum();
int lastRow1 = sheet1.getLastRowNum();
boolean equalSheets = true;
for (int i = firstRow1; i <= lastRow1; i++) {
Reporter.log("\n\nComparing Row " + i);
Add_Log.info("\n\nComparing Row " + i);
XSSFRow row1 = sheet1.getRow(i);
XSSFRow row2 = sheet2.getRow(i);
//row3edit = sheet.getRow(i);
for(int rownum = 0; rownum < 100; rownum++){
row3edit= sheet.createRow(rownum);
}
if (!compareTwoRows(row1, row2, row3edit)) {
equalSheets = false;
// Write if not equal
// Get error here java.lang.NullPointerException for row3edit.setRowStyle(cellStyleRed);
//if disable test is completed Successfully without writing result file
row3edit.setRowStyle(cellStyleRed);
Reporter.log("Row " + i + " - Not Equal");
Add_Log.info("Row " + i + " - Not Equal");
// break;
} else {
Reporter.log("Row " + i + " - Equal");
Add_Log.info("Row " + i + " - Equal");
}
}
// Write if not equal
opstr = new FileOutputStream(""\\\\sd\\comparisonfile\\ResultFile.xlsx");
sxssfWorkbook.write(opstr);
opstr.close();
return equalSheets;
}
// Compare Two Rows
public boolean compareTwoRows(XSSFRow row1, XSSFRow row2, SXSSFRow row3edit) throws IOException {
if ((row1 == null) && (row2 == null)) {
return true;
} else if ((row1 == null) || (row2 == null)) {
return false;
}
int firstCell1 = row1.getFirstCellNum();
int lastCell1 = row1.getLastCellNum();
boolean equalRows = true;
// Compare all cells in a row
for (int i = firstCell1; i <= lastCell1; i++) {
XSSFCell cell1 = row1.getCell(i);
XSSFCell cell2 = row2.getCell(i);
for(int cellnum = 0; cellnum < 10; cellnum++){
Cell = row3edit.createCell(cellnum);
String address = new CellReference(Cell).formatAsString();
Cell.setCellValue(address);
}
if (!compareTwoCells(cell1, cell2)) {
equalRows = false;
Reporter.log(" Cell " + i + " - NOt Equal " + cell1 + " === " + cell2);
Add_Log.info(" Cell " + i + " - NOt Equal " + cell1 + " === " + cell2);
break;
} else {
Reporter.log(" Cell " + i + " - Equal " + cell1 + " === " + cell2);
Add_Log.info(" Cell " + i + " - Equal " + cell1 + " === " + cell2);
}
}
return equalRows;
}
// Compare Two Cells
#SuppressWarnings("deprecation")
public static boolean compareTwoCells(XSSFCell cell1, XSSFCell cell2) {
if ((cell1 == null) && (cell2 == null)) {
return true;
} else if ((cell1 == null) || (cell2 == null)) {
return false;
}
boolean equalCells = false;
int type1 = cell1.getCellType();
int type2 = cell2.getCellType();
if (type2 == type1) {
if (cell1.getCellStyle().equals(cell2.getCellStyle())) {
// Compare cells based on its type
switch (cell1.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
if (cell1.getCellFormula().equals(cell2.getCellFormula())) {
equalCells = true;
} else {
}
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (cell1.getNumericCellValue() == cell2.getNumericCellValue()) {
equalCells = true;
} else {
}
break;
case HSSFCell.CELL_TYPE_STRING:
if (cell1.getStringCellValue().equals(cell2.getStringCellValue())) {
equalCells = true;
} else {
}
break;
case HSSFCell.CELL_TYPE_BLANK:
if (cell2.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
equalCells = true;
} else {
}
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
if (cell1.getBooleanCellValue() == cell2.getBooleanCellValue()) {
equalCells = true;
} else {
}
break;
case HSSFCell.CELL_TYPE_ERROR:
if (cell1.getErrorCellValue() == cell2.getErrorCellValue()) {
equalCells = true;
} else {
}
break;
default:
if (cell1.getStringCellValue().equals(cell2.getStringCellValue())) {
equalCells = true;
} else {
}
break;
}
} else {
return false;
}
} else {
return false;
}
return equalCells;
}
}
in general 40'000 rows is a very small volume of data and I would not
like to suggest employing Streaming in that case.
Instead, you can hold 40'000 rows in a XSSF workbook easily if you just
provide enough memory. Using a XSSF workbook, you can modify the
content directly as you have tried.
However, if you work with really large data of 1 Mill. rows and many
columns, then the following approach will help:
1) engange the Excel Streaming Reader
2) read both files F1 and F2 simultaneously and compare row by row and
cell by cell
3) based on the found difference, create a new row with new cells and
write that to your result file F3
You can not modify existing cells in a SXSSFWorkbook.

For-loop prints only the last value of Array through whole Excel file

I am struggling through this IBAN Checker JAVA project where I am supposed to take IBANs from an excel sheet -> validate them -> print valid/invalid results back into Excel. I have it almost all set up but now I got stuck on looping function that should put already validated IBANS back to the sheet. Here I am getting only last IBAN number of my IBAN Array which gets printed into all the rows, other IBANs are not showing.
However, when I use "System.out.printf("%s is %s.%n", iban, validateIBAN(iban) ? "valid" : "not valid");" function all the ibans are validated correctly and printed into console one by one.
Is there please some way to get the results of above "System.out.printf" and iterate them through the cells in the Excel sheet? Or would you have some suggestion for modifications of the for-loop please? I think something in the loop is causing the issue because when I put "System.out.prinf" function inside of the loop, it starts validating only the last IBAN number which means something with the loop is not right.
Thank you very much for any help you can give!
IBANChecker03.java
package ibanchecker03;
import java.math.BigInteger;
import java.util.*;
//EXCEL
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//EXCEL
public class IBANChecker03 {
private static final String DEFSTRS = ""
+ "AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 "
+ "HR21 CY28 CZ24 DK18 DO28 EE20 FO18 FI18 FR27 GE22 DE22 GI23 "
+ "GL18 GT28 HU28 IS26 IE22 IL23 IT27 KZ20 KW30 LV21 LB28 LI21 "
+ "LT20 LU20 MK19 MT31 MR27 MU30 MC27 MD24 ME22 NL18 NO15 PK24 "
+ "PS29 PL28 PT25 RO24 SM27 SA24 RS22 SK24 SI19 ES24 SE24 CH21 "
+ "TN24 TR26 AE23 GB22 VG24 GR27 CR21";
private static final Map<String, Integer> DEFINITIONS = new HashMap<>();
static {
for (String definition : DEFSTRS.split(" "))
DEFINITIONS.put(definition.substring(0, 2), Integer.parseInt(definition.substring(2)));
}
public static void printValid(String iban) throws FileNotFoundException, IOException, InvalidFormatException {
File file = new File("G:\\AR\\INVprint (GD Thomas)\\EKG.xls");
FileInputStream ExcelFile = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(ExcelFile);
HSSFSheet sheet = wb.getSheet("SheetF");
System.out.printf("%s is %s.%n", iban, validateIBAN(iban) ? "valid" : "not valid");
try {
for (int rowNumber = 0; rowNumber < sheet.getLastRowNum(); rowNumber++) {
HSSFRow row1 = sheet.getRow(rowNumber);
HSSFCell cell = row1.createCell(1);
cell.setCellValue(iban + " is " + validateIBAN(iban));
//System.out.println(cell);
//for(int columnNumber = 1; columnNumber < row1.getLastCellNum();) {
// HSSFCell cell = row1.createCell(columnNumber);
// if(cell != null) {
//cell.setCellValue("Darkness");
//System.out.println(cell);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("G:\\AR\\INVprint (GD Thomas)\\EKG.xls");
wb.write(fileOut);
wb.close();
} catch (FileNotFoundException e) {
throw new FileNotFoundException("File not faaund");
}
}
public static void main(String[] args) throws IOException, FileNotFoundException {
String[] ibans = {"GB33BUKB20201555555555"};
for (String iban : ibans) {
try {
printValid(iban);
} catch (InvalidFormatException ex) {
Logger.getLogger(IBANChecker03.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
static boolean validateIBAN(String iban) {
iban = iban.replaceAll("\\s", "").toUpperCase(Locale.ROOT);
int len = iban.length();
if (len < 4 || !iban.matches("[0-9A-Z]+") || DEFINITIONS.getOrDefault(iban.substring(0, 2), 0) != len)
return false;
iban = iban.substring(4) + iban.substring(0, 4);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++)
sb.append(Character.digit(iban.charAt(i), 36));
BigInteger bigInt = new BigInteger(sb.toString());
return bigInt.mod(BigInteger.valueOf(97)).intValue() == 1;
}
}
HomeOffice.java
package ibanchecker03;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class HomeOffice {
public static void main(String[] args) throws Exception {
File excelFile = new File("G:\\AR\\INVprint (GD Thomas)\\TEST2 IBAN.xlsx");
FileInputStream fis = new FileInputStream(excelFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
//Here we start iterating through raws and cells
Iterator<Row> rowIt = sheet.iterator();
while (rowIt.hasNext()) {
Row row = rowIt.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getColumnIndex() == 7) { // Choose number of column
//System.out.println(cell.toString() + ","); // Print cells
String cellvalue = cell.toString();
IBANChecker03.printValid(cellvalue);
}
}
workbook.close();
fis.close();
}
}
}

how can I solve error while reading Excel xls file in java

I have a Excel file in the location called E:/portfolio.xls. I want to read this file through a java code. I wrote some of the code using java but not able to read that file and showing some error.I am new in these type of coding. Some one please help me to solve these problem.My java code is in bellow:
/SampleExcelReading.java
package com.sampleexcelreading.core;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class SampleExcelReading {
public static void main(String[] args) {
try {
Multimap<String, String> portfolioHoldingMap = ArrayListMultimap.create();
File f=new File("E:/portfolio.xls");
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(f);
int numberOfSheets = workbook.getNumberOfSheets();
org.apache.poi.ss.usermodel.Sheet sheet=null;
sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
String currentSchemeNameCode = "";
String holding_date = "";
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
int rowNo = row.getRowNum();
if(rowNo < 0 || rowNo >= 1500)
{
continue;
}
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
String value = "";
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell))
{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
value = sdf.format(cell.getDateCellValue());
}
else
{
value = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "0";
break;
default:
value = "0";
break;
}
if(cell.getColumnIndex() == 0 && rowNo > 0 && !value.equalsIgnoreCase(""))
{
value = value.trim().replaceAll(" +", " ");
int firstHypenIndex = value.indexOf("-");
value = value.substring(firstHypenIndex + 2, value.length());
int firstAsAtIndex = value.indexOf(" as at ");
holding_date = value.substring(firstAsAtIndex + 7, value.length());
String[] nav_date_splitted = holding_date.split("[\\/]+");
holding_date = nav_date_splitted[2] + "-" + nav_date_splitted[1] + "-" + nav_date_splitted[0];
value = value.substring(0, firstAsAtIndex);
value = value.replaceAll("'","�");
schemeName.add(value.trim());
currentSchemeNameCode = value.trim();
}
if(rowNo == 0 && cell.getColumnIndex() != 0)
{
value = value.replaceAll("'","�");
companyName.add(value);
}
if(rowNo > 0 && cell.getColumnIndex() != 0)
{
portfolioHoldingMap.put(currentSchemeNameCode,cell.getColumnIndex() + "||" + value.trim().replaceAll(" +", " ") + "||" + holding_date);
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/* Here is my Error */
org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException
at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:62)
at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:403)
at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:186)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:91)
at com.advisorkhoj.amfi.SampleExcelReading.main(SampleExcelReading.java:27)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:60)
... 5 more
Caused by: java.io.CharConversionException: Characters larger than 4 bytes are not supported: byte 0x96 implies a length of more than 4 bytes
at org.apache.xmlbeans.impl.piccolo.xml.UTF8XMLDecoder.decode(UTF8XMLDecoder.java:162)
at org.apache.xmlbeans.impl.piccolo.xml.XMLStreamReader$FastStreamDecoder.read(XMLStreamReader.java:762)
at org.apache.xmlbeans.impl.piccolo.xml.XMLStreamReader.read(XMLStreamReader.java:162)
at org.apache.xmlbeans.impl.piccolo.xml.PiccoloLexer.yy_refill(PiccoloLexer.java:3474)
at org.apache.xmlbeans.impl.piccolo.xml.PiccoloLexer.yylex(PiccoloLexer.java:3958)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.yylex(Piccolo.java:1290)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.yyparse(Piccolo.java:1400)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.parse(Piccolo.java:714)
at org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:3439)
at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1270)
at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1257)
at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:345)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.StyleSheetDocument$Factory.parse(Unknown Source)
at org.apache.poi.xssf.model.StylesTable.readFrom(StylesTable.java:121)
at org.apache.poi.xssf.model.StylesTable.<init>(StylesTable.java:92)
... 10 more
/My jar files are
dom4j-1.6.jar
poi-3.9.jar
poi-ooxml-3.9.jar
poi-ooxml-schemas-3.7-betal1.jar
xmlbeans-2.30.jar
Apache POI has only partial support to read Excel xlsb files. It can't be done using a Workbook, but since POI 3.16-beta3 it supports streaming reading of such files via XSSFBReader.

state the create table name in jdbc without .xls

i made a program in java that it takes an excel file and store its data in a database. When i state where the file is its like this:
String filename = "test5.xls";
String path = "C:\\Users\\myfiles\\Documents\\";
But when i call the create table and i state the filename of the excel file because it it test.xls the mysql command shows error!
The create table function is:
try
{
String all = org.apache.commons.lang3.StringUtils.join(allFields, ",");
String createTableStr = "CREATE TABLE " + "table5" + " (" + all + ")";
System.out.println( "Create a new table in the database" );
stmt.executeUpdate( createTableStr );
Is there any way to rename the file before i create the table or to read only the "test" without the .xls?
My program is the below:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class readexcel {
public static void main (String[] args) throws Exception {
//String filename = "C:\\Users\\myfiles\\Documents\\test5.xls";
String filename = "test5.xls";
String path = "C:\\Users\\myfiles\\Documents\\";
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(path + filename);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExcelData(sheetData);
HashMap<String,Integer> tFields = new HashMap();
tFields = parseExcelData(sheetData);
String str = getCreateTable(filename, tFields);
}
private static void showExcelData(List sheetData) {
// HashMap<String, String> tableFields = new HashMap();
for (int i=0; i<sheetData.size();i++){
List list = (List) sheetData.get(i);
for (int j=0; j<list.size(); j++){
Cell cell = (Cell) list.get(j);
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue());
}
else if(cell.getCellType()==Cell.CELL_TYPE_STRING)
{
System.out.print(cell.getRichStringCellValue());
}
else if(cell.getCellType()==Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
}
if (j < list.size() - 1)
{
System.out.print(", ");
}
}
System.out.println("");
}
}
#SuppressWarnings({ "unchecked", "unused" })
private static HashMap parseExcelData (List sheetData){
HashMap<String,Integer> tableFields = new HashMap();
List list = (List) sheetData.get(0);
for (int j=0; j<list.size(); j++){
Cell cell=(Cell) list.get(j);
tableFields.put(cell.getStringCellValue(),cell.getCellType());
}
return tableFields;
}
private static String getCreateTable(String tablename, HashMap<String, Integer> tableFields){
Iterator iter = tableFields.keySet().iterator();
String str="";
String[] allFields = new String[tableFields.size()];
int i = 0;
while (iter.hasNext()){
String fieldName = (String) iter.next();
Integer fieldType=(Integer)tableFields.get(fieldName);
switch (fieldType){
case Cell.CELL_TYPE_NUMERIC:
str=fieldName + " INTEGER";
break;
case Cell.CELL_TYPE_STRING:
str= fieldName + " VARCHAR(255)";
break;
case Cell.CELL_TYPE_BOOLEAN:
str=fieldName + " INTEGER";
break;
}
allFields[i++]= str;
}
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/kainourgia","root", "root");
Statement stmt = con.createStatement();
try
{
System.out.println( "Use the database..." );
stmt.executeUpdate( "USE kainourgia;" );
}
catch( SQLException e )
{
System.out.println( "SQLException: " + e.getMessage() );
System.out.println( "SQLState: " + e.getSQLState() );
System.out.println( "VendorError: " + e.getErrorCode() );
}
try
{
String all = org.apache.commons.lang3.StringUtils.join(allFields, ",");
String createTableStr = "CREATE TABLE " + "table5.xls" + " (" + all + ")";
System.out.println( "Create a new table in the database" );
stmt.executeUpdate( createTableStr );
}
catch( SQLException e )
{
System.out.println( "SQLException: " + e.getMessage() );
System.out.println( "SQLState: " + e.getSQLState() );
System.out.println( "VendorError: " + e.getErrorCode() );
}
}
catch( Exception e )
{
System.out.println( ((SQLException) e).getSQLState() );
System.out.println( e.getMessage() );
e.printStackTrace();
}
return str;
}
#SuppressWarnings({ "unused", "unused", "unused", "unused" })
private Statement createStatement() {
return null;
}
}
Thank you in advance!
Gives name of the file
String filename = "test5.xls";
String path = "C:\\Users\\myfiles\\Documents\\";
File f = new File (path + filename);
System.out.println(f.getName());// gives only file name with out extension

Categories