Insert to mysql with undefined number of column - java

I have a question about insert query of java.
I have read data from excel file, and I want to use that data to import to MySQL, if excel file has 3 columns, I can use
String sql="INSERT INTO tablename(column1,column2,colum3) value(...)
But if excel file doesn't have defined the number of column (for example excel_1.xlsx have 3 columns, excel_2.xlsx have 4 columns).
How can I use insert query? Can anybody give me any suggestion?

You can do something like this:
FileInputStream excelFile = new FileInputStream(new File("yourExcelsheet.xsls"));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
//int columnCount = 4;
String columnArray[] = new String[]{"column1","column2","column3","column4","column5","column6"};
//iterate row-wise
while (iterator.hasNext()) {
String sql="INSERT INTO tablename";
String columnNames = "";
String valueString = "";
String value = "";
int i=0;
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
//iterate column-wise
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
value = currentCell.getStringCellValue();
if(i != 0)
{
columnNames += ",";
valueString += ",";
}
columnNames += columnArray[i] ;
valueString += value;
i++;
}
sql += "(" + columnNames + ") values (" + valueString + ");";
System.out.println(sql);
}
OUTPUT:
INSERT INTO tablename(column1,column2,column3,column4) values
(5,5,5,5);

Related

How to get cell value from the cell which consists of formula in excel xls file

I am writing java code to read excel file and to create an object from that but one column consists of formula when I read cell formula is coming in value field instead of value
I tried to get from cell index
I tried to get value from iterator(hasnext()) method :
like:
public static void CheckDuplicate(File file) throws Exception {
Set newReordsList = new LinkedHashSet();
LinkedHashMap<String, DataCleansingObject> lhm = new LinkedHashMap<String, DataCleansingObject>();
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
HSSFRow row;
Iterator< Row> rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
row = (HSSFRow) rowIterator.next();
if(row.getRowNum() == 0) {
continue;
}
DataCleansingObject dataObj = new DataCleansingObject();
Iterator< Cell> cellIterator = row.cellIterator();
String key = "";
if (cellIterator.hasNext()) {
dataObj.setDocType(row.getCell(1).toString());
dataObj.setDocNo(row.getCell(2).toString());
dataObj.setDocVer(Long.parseLong(row.getCell(3).toString()));
dataObj.setDocPart(row.getCell(4).toString());
dataObj.setDocLang(row.getCell(5).toString());
dataObj.setDocRev(row.getCell(6).toString());
dataObj.setDocStatus(row.getCell(7).toString());
dataObj.setDocSD(row.getCell(8).toString());
dataObj.setDocLD(row.getCell(9).toString());
dataObj.setDocChangeNumber(row.getCell(10).toString());
key = row.getCell(1).toString() + "_" + row.getCell(2).toString() + "_" + row.getCell(3).toString() + "_" + row.getCell(4).toString();
}
lhm.put(key, dataObj);
}
fis.close();
copyInExcel(newReordsList);
}
When ever I call below line
Long.parseLong(row.getCell(3).toString())
I need to get long value not formula in that cell

Copying of two different excel sheets to one sheet using Java

Copying of two different excel sheets to one new excel sheet using Java code is resulting in partial output.
This is for Java code running in IntelliJ, using Apache POI.
public static void copySheet(XSSFSheet inputSheet1, XSSFSheet outputSheet, XSSFSheet inputSheet2)
{
int rowCount = inputSheet1.getLastRowNum();
int rc = inputSheet2.getLastRowNum(),rcnt=0,cri =0,l=0;
int currentRowIndex = 0, cell = 0;
if (rowCount > 0) {
Iterator rowIterator = inputSheet1.iterator();
while (rowIterator.hasNext()) {
int currentCellIndex = 0;
Iterator cellIterator;
Row row = (Row) rowIterator.next();
cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
//Creating new Row, Cell and Input value in the newly created sheet.
String cellData = cellIterator.next().toString();
if (currentCellIndex == 0)
outputSheet.createRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
else
outputSheet.getRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
currentCellIndex++;
System.out.println("content test2 " + cellData);
System.out.println("current row index " + currentRowIndex);
System.out.println("current cell " + cell);
}
currentRowIndex++;
cell = currentCellIndex;
rcnt = cell;
}
}
cri = 0;
if (rc > 0) {
Iterator rowIterator = inputSheet2.iterator();
while (rowIterator.hasNext()) {
int currentCellIndex2 = 0,cci = rcnt+1;
Iterator cellIterator2;
Row row = (Row) rowIterator.next();
cellIterator2 = row.cellIterator();
while (cellIterator2.hasNext()) {
String cellData = cellIterator2.next().toString();
if (currentCellIndex2 == 0)
outputSheet.createRow(cri).createCell(cci).setCellValue(cellData);
else
outputSheet.getRow(cri).createCell(cci).setCellValue(cellData);
currentCellIndex2 = currentCellIndex2+1;
cci = cci +1;
System.out.println("content "+cellData);
System.out.println("current row index " + cri);
}
cri++;
}
}
}
Expected output :
both the sheets should be copied to the new sheet.
Actual output :
only the second input sheet is copied to the new sheet.
If I try to copy one the first sheet it will be copied. But if I try to copy both only second sheet will be present.
Input_one
Input_two
Output
It looks like you are overwriting output of the first while loop with the output of the second because in one you use currentRowIndex and in the second you use cri. Reuse the currentRowIndex for the second while-loop as well, so that the rows from the second sheet get appended after the ones for the first one.

Java - Eclipse to Excel from SQL Query

Getting the results of a SQL query where I want row 5 from every record that is returned.
I would like to export the data to an Excel spreadsheet in rows of thirteen, starting at the second row (I have headers).
My SQL logic is obviously off right now because I'm getting the first result thirteen times in increasing rows and columns, although it is properly starting on the second row and only going out 13 columns. The second result repeats in this fashion, as does each successive result.
I suspect my troubles start at while (rs.next()) {
for (int i = 0; i < 13; i++) {
package process;
import java.util.Scanner;
import java.io.*;
import java.sql.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
public class Sec_Completions {
public static void main(String[] args) {
Sec_Completions obj_Sec_Completions=new Sec_Completions();
obj_Sec_Completions.Check_Data();
}
public void Check_Data() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the beginning date of completion YYYY/MM/DD");
String doc = scanner.nextLine();
doc = doc + " 00:00";
System.out.println("Date is" + " " + doc);
final String sql = "SELECT DISTINCT wp_grassblade_completions.user_id, wp_grassblade_completions.status, wp_grassblade_completions.content_id, wp_usermeta.meta_key, CASE WHEN meta_value = 'male' THEN 'M' WHEN meta_value = 'female' THEN 'F' WHEN meta_value = 'Louisiana' THEN 'LA' ELSE meta_value END AS '1', wp_usermeta.meta_value, wp_usermeta.user_id, wp_grassblade_completions.timestamp\r\n" +
"FROM wp_grassblade_completions \r\n" +
"INNER JOIN wp_usermeta ON wp_grassblade_completions.user_id = wp_usermeta.user_id\r\n" +
"WHERE wp_grassblade_completions.timestamp >= ? AND meta_key IN ('mepr_full_name', 'mepr_address', 'mepr_city', 'mepr_state', 'mepr_zip_code', 'mepr_home_phone_with_area_code', \r\n" +
" 'mepr_drivers_license_or_id', 'mepr_id_state', 'mepr_LAst_four_of_social_security_number', 'mepr_date_of_birth_mmddyyyy', 'mepr_sex_mf', 'mepr_height', 'mepr_weight') AND content_id IN ('1575, 642, 1580') \r\n" +
"ORDER BY wp_grassblade_completions.timestamp, content_id, wp_usermeta.user_id";
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://wpengine.com:3306/wp_database","user", "passsword");
PreparedStatement ps =null;
ps=connection.prepareStatement(sql);
ps.setString(1, doc);
Statement st = connection.createStatement();
ResultSet rs = ps.executeQuery();
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Security");
XSSFRow rowhead = sheet.createRow((short) 0);
int index = 1;
while (rs.next()) {
for (int i = 0; i < 13; i++) {
XSSFRow row = sheet.createRow((short) index);
row.createCell((short) i).setCellValue(rs.getString(5));
index++;
}
}
FileOutputStream fileOut = new FileOutputStream("D://OneDrive//ABSEC//ATC_Reporting//expdata1.xlsx");
wb.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
rs.close();
connection.close();
} catch (Exception e) {
System.out.println(e);
}
Edited, again
Try something like this:
// META_KEY values, in the order that the columns should be. This should be a
// private static final outside of in the class, along with the query's text...
String[] keys = { "mepr_full_name", "mepr_address", "mepr_city", "mepr_state",
"mepr_zip_code", "mepr_home_phone_with_area_code",
"mepr_drivers_license_or_id", "mepr_id_state",
"mepr_LAst_four_of_social_security_number", "mepr_date_of_birth_mmddyyyy",
"mepr_sex_mf", "mepr_height", "mepr_weight" };
// Running thru the ResultSet
short index = 1;
while ( rs.next() )
{
XSSFRow row = sheet.createRow( index );
String key = rs.getString(4); // meta_key
String value = rs.getString( 5 ); // meta_value
for ( short i = 0; i < keys.length; ++i )
{
if ( keys[i].equals( key))
{
// Retrieving cell, creating if not exists
XSSFCell cell = row.getCell( i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK );
// if the cell is used, increment index o get to the next row
if ( cell.getCellTypeEnum() != CellType.BLANK )
++index;
// Set the value
cell.setCellValue( value );
// No need to walk thru the rest of the array...
break;
}
}
}
This only works, tho, if any "next row" does not start with a column that has no value in the previous row...
For this reason you should also add meta_key to the ORDER BY clause...
With some additional cleanup, something like this:
SELECT DISTINCT wpgc.user_id, wpgc.status, wpgc.content_id, wpu.meta_key,
CASE wpu.meta_value WHEN 'male' THEN 'M' WHEN 'female' THEN 'F'
WHEN 'Louisiana' THEN 'LA' ELSE wpu.meta_value END AS '1',
wpu.user_id, wpgc.timestamp
FROM wp_grassblade_completions AS wpgc
JOIN wp_usermeta AS wpu ON wpgc.user_id = wpu.user_id
WHERE wpgc.timestamp >= ?
AND wpu.meta_key IN ('mepr_full_name', 'mepr_address', 'mepr_city', 'mepr_state',
'mepr_zip_code', 'mepr_home_phone_with_area_code',
'mepr_drivers_license_or_id', 'mepr_id_state',
'mepr_LAst_four_of_social_security_number',
'mepr_date_of_birth_mmddyyyy', 'mepr_sex_mf', 'mepr_height',
'mepr_weight')
AND content_id IN ('1575, 642, 1580')
ORDER BY wpgc.timestamp, wpgc.content_id, wpu.user_id, wpu.meta_key

in excel empty cells of non empty rows are neglected using java , POI jars

Excel To Json Conversion using JAVA, POI
Issue: Empty cells in Non Empty rows are neglected.
I am trying to convert an excel file through java to Json.A2 and B2 cells are empty but these cells are negleted i want even these cells to be counted and return an empty string
output obtained, the 2nd row starts from C2 by neglecting A2 and B2 which has empty values
public static String ExcelToJsonConverter(String filePath) throws Exception {
try {
FileInputStream inp = new FileInputStream(filePath);
Workbook workbook = WorkbookFactory.create(inp);
Sheet sheet = workbook.getSheetAt(0);
JSONArray rows = new JSONArray();
int coun = 0;
for (Iterator < Row > rowsIT = sheet.rowIterator(); rowsIT.hasNext();)
{
Row row = rowsIT.next();
JSONObject jRow = new JSONObject();
JSONArray cells = new JSONArray();
for (Iterator < Cell > cellsIT = row.cellIterator(); cellsIT.hasNext();) {
coun++;
Cell cell = cellsIT.next();
String val = "";
if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
System.out.println("Formula is " + cell.getCellFormula());
switch (cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Last evaluated as: " + cell.getNumericCellValue());
val = Double.toString(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
val = cell.getStringCellValue();
break;
}
} else if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
val = " ";
} else {
val = formatter.formatCellValue(cell);
}
enter code here
cells.put(val);
}
jRow.put("", cells);
rows.put(jRow);
}
json.put("", rows);
} catch (Exception e) {
//throw new BsfConstraintViolationException("Please Upload a valid file."+e.getMessage());
throw new BsfConstraintViolationException("Please Upload a valid file using Download Default BOQ option");
}
String formatJson = json.toString().replace("\"\":", "");
formatJson = formatJson.toString().replace("{", "");
formatJson = formatJson.toString().replace("}", "");
formatJson = formatJson.substring(1, formatJson.length() - 1);
return formatJson;
}
Advance Thanks to all

Apache POI find last cell in row

I have the following code that reads a spreadsheet and writes to pipe-delimeted file. Rows have differing length. The last cell shouldn't get appended with a pipe character (but does). I tried things like https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getLastCellNum() but cannot make it work.
XSSFWorkbook wb = new XSSFWorkbook(pathandfilename);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
XSSFSheet sheet = wb.getSheetAt(i);
String outfilename = path + "\\" + prefix + sheetname + postfix;
PrintWriter outfilewriter = new PrintWriter(outfilename, "UTF-8");
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
outfilewriter.print(cell.getStringCellValue() + "|");
}
outfilewriter.print("\n");
}
outfilewriter.close();
}
wb.close();
I fixed it as such:
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> recordArry = new ArrayList<String>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
recordArry.add(cell.getStringCellValue() + "|");
}
StringBuilder recordString = new StringBuilder();
for (String elem : recordArry) {
recordString.append(elem);
}
String recordString2 = StringUtils.chomp(recordString.toString(), "|");
outfilewriter.print(recordString2);
outfilewriter.print("\n");
}

Categories