How to read empty cell in Excel file using POI? - excel

How to read empty cell in excel file using POI?
When I upload Excel file, the empty cell is filled with previous cell.
like this:
this is the sample of excel file
this is the DB that the empty cell be filled with previous cell
POI VERSION
org.apache.poi
poi
4.1.2
org.apache.poi
poi-ooxml
4.1.2
code
#RequestMapping("/mng/mngSaupExcelUpload14.do")
public ModelAndView mngBizApplyExcelUpload14(MultipartHttpServletRequest request, HttpServletResponse response,
HttpSession session, INDEYearVO attach) throws IOException, ParseException {
Iterator<String> iterator = request.getFileNames();
int actResult = 0;
ModelAndView mav = new ModelAndView();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
MultipartFile mFile = null;
while (iterator.hasNext()) {
String uploadFileName = iterator.next();
mFile = request.getFile(uploadFileName);
// String originFileName = mFile.getOriginalFilename();
// String saveFileName = originFileName;
}
XSSFWorkbook workbook = new XSSFWorkbook(mFile.getInputStream());
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
XSSFSheet sheet = workbook.getSheetAt(sheetNum);
int rows = sheet.getPhysicalNumberOfRows();
int rowindex = 0;
int columnindex = 0;
if (sheetNum == 0) {
for (rowindex = 1; rowindex < rows; rowindex++) {
sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.getRow(rowindex);
if (row != null) {
int cells = row.getPhysicalNumberOfCells();
for (columnindex = 0; columnindex <= cells; columnindex++) {
XSSFCell cell = row.getCell(columnindex);
String value = "";
if (cell == null) {
continue;
} else {
switch (cell.getCellType()) {
case FORMULA:
value = cell.getCellFormula();
break;
case NUMERIC:
//value = (int)cell.getNumericCellValue() + "";
double cellValue = cell.getNumericCellValue();
if (cellValue == Math.rint(cellValue)) {
value = String.valueOf((int) cellValue);
} else {
value = String.valueOf(cellValue);
}
break;
case STRING:
value = cell.getStringCellValue() + "";
break;
case BLANK:
value = null;
// value = cell.getBooleanCellValue() + "";
break;
case ERROR:
value = cell.getErrorCellValue() + "";
break;
default:
}
if (columnindex == 0) {
attach.setSn(Integer.parseInt(value));
}else if (columnindex == 1) {
attach.setYear(Integer.parseInt(value));
}else if (columnindex == 2) {
attach.setSigngu(value);
} else if (columnindex == 3) {
attach.setJan(Integer.parseInt(value));
} else if (columnindex == 4) {
attach.setFeb(Integer.parseInt(value));
} else if (columnindex == 5) {
attach.setMar(Integer.parseInt(value));
} else if (columnindex == 6) {
attach.setApr(Integer.parseInt(value));
} else if (columnindex == 7) {
attach.setMay(Integer.parseInt(value));
} else if (columnindex == 8) {
attach.setJne(Integer.parseInt(value));
} else if (columnindex == 9) {
attach.setJly(Integer.parseInt(value));
} else if (columnindex == 10) {
attach.setAug(Integer.parseInt(value));
} else if (columnindex == 11) {
attach.setSep(Integer.parseInt(value));
} else if (columnindex == 12) {
attach.setOct(Integer.parseInt(value));
} else if (columnindex == 13) {
attach.setNov(Integer.parseInt(value));
} else if (columnindex == 14) {
if ("false".equals(value) || "".equals(value) || "0".equals(value) || value == null ) {
attach.setDec(Integer.parseInt(""));
} else {
attach.setDec(Integer.parseInt(value));
}
}
}
}
actResult = attachFileService.fileInsertActForExcel14(attach);
}
}
}
}
if (actResult > 0) {
out.println("<script>");
out.println("alert('등록에 성공 하였습니다.');");
out.println("location.replace('" + request.getContextPath() + "attachFile.do');");
out.println("</script>");
out.flush();
out.close();
return null;
} else {
out.println("<script>");
out.println("alert('등록 중 오류가 발생했습니다.');");
out.println("location.replace('" + request.getContextPath() + "attachFile.do');");
out.println("</script>");
out.flush();
out.close();
return null;
}
}
I don't really know why empty cell is filled..

I don't think it's a problem with poi. Also check the db insert code.
And I'm developing a library that might be helpful, so I'd appreciate it if you could watch it.
https://github.com/scndry/jackson-dataformat-spreadsheet

Related

Excel loses styles and formating after writing certain rows using apache poi library

I am trying to create a excel file(.xls) while writing a excel for tolal of 9000 rows, after row number 3000 all the styles and formatting are lost.
I have tried to get the number of cellstyle after writing the complete workbook by using workbook.getNumCellStyles(), it returns 2091.
It is clear that the number of cellstyle are not exceeded(i.e are less than 4000)
Still the styling is lost.
Please help me understand why would this happen?
I have created a Sample code, below this fails even if i am creating 75 CellStyle Objects.
public class ExcelSheet {
static Workbook workbook;
static Sheet spreadsheet;
static CellStyle tempCellStyle;
static Map<Integer, CellStyle> styles = new HashMap<Integer, CellStyle>();
static boolean flag = false;
public static void main(String[] args) throws IOException {
workbook = new HSSFWorkbook();
spreadsheet = workbook.createSheet(" Employee Info ");
Row row;
System.out.println(" Writing data to excel...");
for (int i = 1; i < 500; i++) {
row = spreadsheet.createRow(i);
createCells(row, i);
}
for (int i = 0; i < 10; i++) {
spreadsheet.setColumnWidth(i, 4500);
}
FileOutputStream out = new FileOutputStream(new File("E:\\Dan\\Writesheet.xls"));
System.out.println(" No. of cell styles : " + workbook.getNumCellStyles());
System.out.println(" No. of font styles : " + workbook.getNumberOfFonts());
workbook.write(out);
out.close();
}
private static void createCells(Row row, int rowNo) {
for (int i = 0; i < 10; i++) {
Cell cell = row.createCell(i);
try {
writeData(cell, i, rowNo);
} catch (Exception e) {
System.out.println("Exception : " + e);
}
}
}
private static void writeData(Cell cell, int i, int rowNo) throws Exception {
CellStyle style;
if (workbook.getNumCellStyles() < 75) {
style = createStyleObject();
} else {
style = null;
}
switch (i) {
case 0:
if (style == null) {
style = styles.get(0);
} else {
styles.put(0, style);
}
cell.setCellValue(rowNo);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(style);
break;
case 1:
if (style == null) {
style = styles.get(1);
} else {
styles.put(1, style);
}
cell.setCellValue("Test Data " + rowNo);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(style);
styles.put(0, style);
break;
case 2:
if (style == null) {
style = styles.get(2);
} else {
styles.put(2, style);
}
DataFormat poiFormat = spreadsheet.getWorkbook().createDataFormat();
String excelFormatPattern = DateFormatConverter.convert(Locale.US, "yyyy-MM-dd");
style.setDataFormat(poiFormat.getFormat(excelFormatPattern));
cell.setCellValue(new Date(rowNo % 10, rowNo % 12, rowNo % 28, rowNo % 12, rowNo % 60, rowNo % 60));
cell.setCellStyle(style);
break;
case 3:
if (style == null) {
style = styles.get(3);
} else {
styles.put(3, style);
}
cell.setCellValue(rowNo + rowNo);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(style);
break;
case 4:
if (style == null) {
style = styles.get(4);
} else {
styles.put(4, style);
}
cell.setCellValue("Sample Text " + rowNo);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(style);
break;
case 5:
if (style == null) {
style = styles.get(5);
} else {
styles.put(5, style);
}
DataFormat poiFormat1 = spreadsheet.getWorkbook().createDataFormat();
String excelFormatPattern1 = DateFormatConverter.convert(Locale.US, "yyyy-MM-dd");
style.setDataFormat(poiFormat1.getFormat(excelFormatPattern1));
cell.setCellValue(new Date(rowNo % 18, rowNo % 12, rowNo % 28, rowNo % 12, rowNo % 60, rowNo % 60));
cell.setCellStyle(style);
break;
case 6:
if (style == null) {
style = styles.get(6);
} else {
styles.put(6, style);
}
cell.setCellValue(rowNo + i);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(style);
break;
case 7:
if (style == null) {
style = styles.get(7);
} else {
styles.put(7, style);
}
cell.setCellValue("Exports Data " + rowNo);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(style);
break;
case 8:
if (style == null) {
style = styles.get(8);
} else {
styles.put(8, style);
}
DataFormat poiFormat2 = spreadsheet.getWorkbook().createDataFormat();
String excelFormatPattern2 = DateFormatConverter.convert(Locale.US, "yyyy-MM-dd");
style.setDataFormat(poiFormat2.getFormat(excelFormatPattern2));
cell.setCellValue(new Date(rowNo % 25, rowNo % 12, rowNo % 28, rowNo % 12, rowNo % 60, rowNo % 60));
cell.setCellStyle(style);
break;
case 9:
if (style == null) {
style = styles.get(9);
} else {
styles.put(9, style);
}
DataFormat poiFormat3 = spreadsheet.getWorkbook().createDataFormat();
String excelFormatPattern3 = DateFormatConverter.convert(Locale.US, "yyyy-MM-dd");
style.setDataFormat(poiFormat3.getFormat(excelFormatPattern3));
cell.setCellValue(new Date());
cell.setCellStyle(style);
break;
default:
if (style == null) {
style = styles.get(7);
} else {
styles.put(7, style);
}
cell.setCellValue("Default Value " + rowNo);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(style);
break;
}
}
private static CellStyle createStyleObject() {
Workbook workbook = spreadsheet.getWorkbook();
CellStyle style = (HSSFCellStyle) workbook.createCellStyle();
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor((short) 67);
style.setWrapText(true);
return style;
}
}
Don't create CellStyle for every cell in the workbook. Instead prepare all possible and unique CellStyles and reuse them.
E.g.:
var cellStyle = createStyleObject();
// ... some customization of the above style
for (int i = 0; i < 10; i++) {
Cell cell = row.createCell(i);
cell.setStyle(cellStyle);
}

Apache POI : Copy data to Particular sheet at particular cell with Merged Columns in Source Sheet

Problem
How to add some part of data from source excel sheet to the destination excel sheet using Apache POI(XSSF Format)?Excel sheet contains merged columns.
Requirement:
Requirement is not only to copy the row but also to put the data into desired Excel cell(desired column) of the destination sheet.
Note
-Copying row to desired row location in destination excel sheet is achievable. Problem is to first merge the cell as per source sheet in destination sheet and then put data into desired merged excel cell.
- Merged Columns could vary in a row.
Here is the source code, half referred and half written.
public static void copyNodeFrmtSrcToDest(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRowStart,XSSFRow srcRowEnd
,XSSFRow destRowStart, int destCellStart, Map<Integer, XSSFCellStyle> styleMap){
/*Check if there is only one row to be pasted*/
int noOfRows = srcRowEnd.getRowNum() - srcRowStart.getRowNum();
/*Check if there is only one row to be pasted*/
if(noOfRows == 0)
{
/*Copy a single row*/
copyRow(srcSheet,destSheet,srcRowStart,destRowStart,destCellStart,styleMap);
return;
}
for (int i = 0;i <= noOfRows ;i++)//For every row
{
/*Get rows from source sheet and increment it*/
XSSFRow srcIntermediateRow = srcSheet.getRow(srcRowStart.getRowNum() + i);
if(destRowStart == null)
{
try {
throw new RowNotFoundError("Row has not been found in the sheet.Kindly create a row.");
} catch (RowNotFoundError e) {
e.printStackTrace();
System.out.println(e.toString());
}
}
if(i!=0)//Assuming destRowStart has been created by user of the API
{
/*Create a new row*/
destRowStart = destSheet.createRow(destRowStart.getRowNum()+1);
}
copyRow(srcSheet,destSheet,srcIntermediateRow,destRowStart,destCellStart,styleMap);
}
}
public static void copyRow(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRow, XSSFRow destRow, int destCellStart,
Map<Integer, XSSFCellStyle> styleMap) {
int count = 1;
Set<CellRangeAddress> mergedRegions = new HashSet<CellRangeAddress>();
CellRangeAddress previousMergedRegion =null;
destRow.setHeight(srcRow.getHeight());
for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {
int mergedDiff;
XSSFCell oldCell = srcRow.getCell(j);
XSSFCell newCell;
if(j == srcRow.getFirstCellNum()){
newCell = destRow.getCell(destCellStart);}
else
{
newCell = destRow.getCell(destCellStart + count);
}
if (oldCell != null) {
if (newCell == null) {
if(j == srcRow.getFirstCellNum()){
newCell = destRow.createCell(destCellStart);//Keeping the new cell as the first one.
copyCell(oldCell, newCell, styleMap);
}
else{
newCell = destRow.createCell(destCellStart + count);
count = count + 1;
copyCell(oldCell, newCell, styleMap);}
}
CellRangeAddress mergedRegion = getMergedRegion(srcSheet, srcRow.getRowNum(),oldCell.getColumnIndex());
if(previousMergedRegion != null && mergedRegion != null)
{
mergedDiff = mergedRegion.getLastColumn() - mergedRegion.getFirstColumn();
if(!previousMergedRegion.equals(mergedRegion))
{
destCellStart = destCellStart + mergedDiff + 1;
count = 1;
}
}
if (mergedRegion != null) {
previousMergedRegion = mergedRegion.copy();
mergedDiff = mergedRegion.getLastColumn() - mergedRegion.getFirstColumn();
CellRangeAddress newMergedRegion = new CellRangeAddress(destRow.getRowNum(),destRow.getRowNum()
,destCellStart,destCellStart + mergedDiff);
if (isNewMergedRegion(newMergedRegion, mergedRegions))
{
mergedRegions.add(newMergedRegion);
destSheet.addMergedRegion(newMergedRegion);
}
}
}
}
}
public static void copyCell(XSSFCell oldCell, XSSFCell newCell, Map<Integer, XSSFCellStyle> styleMap) {
if(styleMap != null) {
if(oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()){
newCell.setCellStyle(oldCell.getCellStyle());
} else{
int stHashCode = oldCell.getCellStyle().hashCode();
XSSFCellStyle newCellStyle = styleMap.get(stHashCode);
if(newCellStyle == null){
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
newCell.setCellStyle(newCellStyle);
}
}
switch(oldCell.getCellTypeEnum()) {
case STRING:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case BLANK:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
default:
break;
}
}
public static CellRangeAddress getMergedRegion(XSSFSheet sheet, int rowNum, int cellNum) {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress merged = sheet.getMergedRegion(i);
if (merged.isInRange(rowNum, cellNum)) {
return merged;
}
}
return null;
}
private static boolean isNewMergedRegion(CellRangeAddress newMergedRegion, Set<CellRangeAddress> mergedRegions)
{
if(mergedRegions.isEmpty())
{
return true;
}
return !mergedRegions.contains(newMergedRegion);
}
}
It is working fine for some testcases but not for all.

How to display container contains tablelayout of 7 columns in center of the screen for all resolution screens in code name one

Currently we are displaying the container that contains the table layout with 7 columns in center of the screen in the 1280x800 pixels resolution.
But we need the same container displaying in the 1920x1200 pixels resolution in center of the screen.
Actually the container is displayed but the row data is missing. Is anything wrong in my code? Please help me how to resolve this one.
FlowLayout centerLayout = new FlowLayout();
centerLayout.setAlign(Component.CENTER);
centerLayout.setValign(Component.TOP);
Container centerContainer = new Container(centerLayout);
topTabelcontainer = new Container(new TableLayout(7, 1));
commonComponentsForm = new CommonComponentsForm();
eventPostSchedulesForm = commonComponentsForm.setEventPostSchedulesFormHeader(eventPostSchedulesForm, res, workerBreaksPreferences);
topTabelcontainer = commonComponentsForm.getEventInfoHeader(eventPostSchedulesForm, res, topTabelcontainer, "showroster");
filterLayoutContainer = this.getFilterBody();
postScheduleTableContainer = this.getEventPostScheduleTable();
TableLayout.Constraint postScheduleTableConstraint = new TableLayout.Constraint();
postScheduleTableConstraint.setHorizontalAlign(BorderLayout.CENTER_BEHAVIOR_SCALE);
postScheduleTableConstraint.setVerticalAlign(BorderLayout.CENTER_BEHAVIOR_SCALE);
topTabelcontainer.add(filterLayoutContainer);
headerContainer);
topTabelcontainer.add(postScheduleTableConstraint, postScheduleTableContainer);
centerContainer.add(topTabelcontainer);
centerContainer.setScrollableY(Boolean.TRUE);
centerContainer.setTactileTouch(Boolean.TRUE);
centerContainer.addPointerDraggedListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
float val = Display.getInstance().getDragSpeed(false);
boolean upperFlag = false;
if (Display.getInstance().isPortrait()) {
if (portRaitUpperBound < toralRecourdsCount)
upperFlag = true;
} else if (landScapeUpperBound < toralRecourdsCount)
upperFlag = true;
boolean lowerFlag = false;
if (Display.getInstance().isPortrait()) {
if ((portRaitLowerBound > 0 && portRaitLowerBound <= toralRecourdsCount))
lowerFlag = true;
} else if (landScapeLowerBound > 0 && landScapeLowerBound < toralRecourdsCount)
lowerFlag = true;
if (val >= 0.5 && scrollFlag) {
dragFlag = true;
if (upperFlag) {
scrollFlag = false;
setPageUpperAndLowerBound(Constants.NEXTFLAG);
postScheduleTableContainer.removeAll();
setEventPostScheduleTable(postScheduleTableContainer);
eventPostSchedulesForm.revalidate();
}
} else if (val <= -0.5 && scrollFlag) {
dragFlag = true;
if (lowerFlag) {
scrollFlag = false;
setPageUpperAndLowerBound(Constants.PREVIOUSFLAG);
postScheduleTableContainer.removeAll();
setEventPostScheduleTable(postScheduleTableContainer);
eventPostSchedulesForm.revalidate();
}
}
}
});
eventPostSchedulesForm.setUIID("workersListForm");
eventPostSchedulesForm.add(BorderLayout.CENTER, centerContainer);
commonComponentsForm.getFooterTag(eventPostSchedulesForm);
eventPostSchedulesForm.show();
}
public Container getEventPostSchedulesTableHeader(Container postSchedulesTableHeaderContainer) {
Label position = new Label(Constants.POSITION, searchingButtonImage);
Label name = new Label(Constants.NAME, searchingButtonImage);
Label callInOutLabel = new Label(Constants.CALLINOUT);
position.setTextPosition(LEFT);
name.setTextPosition(LEFT);
TextArea actualCallIn1 = null;
Label actualCallIn = null;
TextArea actualCallOut1 = null;
Label actualCallOut = null;
TextArea agencyWorker1 = null;
Label agencyWorker = null;
if (Display.getInstance().isPortrait()) {
actualCallIn1 = new TextArea(Constants.ACTUALCALLIN);
actualCallIn1.setEditable(false);
actualCallIn1.setFocusable(false);
actualCallIn1.setColumns(3);
actualCallIn1.setVerticalAlignment(Component.CENTER);
actualCallOut1 = new TextArea(Constants.ACTUALCALLOUT);
actualCallOut1.setEditable(false);
actualCallOut1.setFocusable(false);
actualCallOut1.setColumns(3);
actualCallOut1.setVerticalAlignment(Component.CENTER);
agencyWorker1 = new TextArea(Constants.AGENCYWORKER);
agencyWorker1.setEditable(false);
agencyWorker1.setFocusable(false);
agencyWorker1.setColumns(3);
agencyWorker1.setVerticalAlignment(Component.CENTER);
} else {
agencyWorker = new Label(Constants.AGENCYWORKER);
actualCallIn = new Label(Constants.ACTUALCALLIN);
actualCallOut = new Label(Constants.ACTUALCALLOUT);
}
Label workerBreak = new Label(" ");
position.setUIID("workerTableHeader");
name.setUIID("workerTableHeader");
callInOutLabel.setUIID("workerTableHeader");
if (Display.getInstance().isPortrait()) {
agencyWorker1.setUIID("workerTableHeader");
actualCallIn1.setUIID("workerTableHeader");
actualCallOut1.setUIID("workerTableHeader");
} else {
agencyWorker.setUIID("workerTableHeader");
actualCallIn.setUIID("workerTableHeader");
actualCallOut.setUIID("workerTableHeader");
}
workerBreak.setUIID("workerTableHeader");
if (Display.getInstance().isPortrait()) {
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(16, 8), position);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(15, 8), name);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(24, 8), callInOutLabel);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 8), actualCallIn1);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 8), actualCallOut1);
postSchedulesTableHeaderContainer.add(getTableConstraint(13, 8), agencyWorker1);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(6, 8), workerBreak);
} else {
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), position);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(18, 10), name);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(20, 10), callInOutLabel);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), actualCallIn);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), actualCallOut);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(16, 10), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(7, 10), workerBreak);
}
return postSchedulesTableHeaderContainer;
}
public Container getEventPostScheduleTable() {
List < WorkerBean > eventPostSchedulesList = null;
roasterDao = RoasterDao.getInstance();
if (Display.getInstance().isPortrait()) {
eventPostSchedulesList = roasterDao.getEventPostSchedulesDetails(positionFilterValue, nameFilterValue, portRaitLowerBound, portRaitPageSize);
} else {
eventPostSchedulesList = roasterDao.getEventPostSchedulesDetails(positionFilterValue, nameFilterValue, landScapeLowerBound, landScapePageSize);
}
int tableRowCount = Constants.INITIALTABLEROWS;
boolean pagingFlag = false;
int eventPostScheduleCount = roasterDao.getEventPostSchedulesCount(positionFilterValue, nameFilterValue);
this.toralRecourdsCount = eventPostScheduleCount;
FlowLayout centerLayout = new FlowLayout();
centerLayout.setAlign(Component.CENTER);
postScheduleTableContainer = new Container(centerLayout);
postScheduleTableContainer.setUIID("tableBodyContainer");
if (eventPostSchedulesList.size() > landScapePageSize) {
tableRowCount = landScapePageSize + 1;
} else {
tableRowCount = eventPostSchedulesList.size() + 1;
}
Container borderTopPagingContainer = new Container(new BorderLayout());
if (eventPostScheduleCount > landScapePageSize) {
pagingFlag = true;
if (Display.getInstance().isPortrait()) {
borderTopPagingContainer = this.setHeaderPaging(eventPostScheduleCount, portRaitLowerBound, portRaitUpperBound, res);
} else {
borderTopPagingContainer = this.setHeaderPaging(eventPostScheduleCount, landScapeLowerBound, landScapeUpperBound, res);
}
}
if (pagingFlag) {
tableRowCount = tableRowCount + 1;
}
int columnCount = 6;
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
columnCount++;
Container postSchedulesListContainer = new Container(new TableLayout(tableRowCount, columnCount));
if (pagingFlag) {
TableLayout.Constraint postSchedulesListConstraint1 = new TableLayout.Constraint();
postSchedulesListConstraint1.setHorizontalSpan(columnCount);
postSchedulesListContainer.add(postSchedulesListConstraint1, borderTopPagingContainer);
}
postSchedulesListContainer = this.getEventPostSchedulesTableHeader(postSchedulesListContainer);
String callInDBValue = "";
String callOutDBValue = "";
String actCallInDBValue = "";
String actCallOutDBValue = "";
Label position = null;
Label name = null;
Label callInOutLabel = null;
Label actualCallIn = null;
Label actualCallOut = null;
TextField agencyWorker = null;
Label workerBreak = null;
for (WorkerBean eventPostSchedules: eventPostSchedulesList) {
callInDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getCallIn().length() > 10)
callInDBValue = eventPostSchedules.getCallIn().substring(10).trim();
else {
if (Constants.PLATFORMNAME.equals(Display.getInstance().getPlatformName()))
callInDBValue = " ";
else
callInDBValue = " ";
}
}
callOutDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getCallOut().length() > 10)
callOutDBValue = eventPostSchedules.getCallOut().substring(10).trim();
else {
if (Constants.PLATFORMNAME.equals(Display.getInstance().getPlatformName()))
callOutDBValue = " ";
else
callOutDBValue = " ";
}
}
actCallInDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getActCallIn().length() > 10)
actCallInDBValue = eventPostSchedules.getActCallIn().substring(10).trim();
else
actCallInDBValue = eventPostSchedules.getActCallIn().trim();
}
actCallOutDBValue = "";
if (null != eventPostSchedules) {
if (eventPostSchedules.getActCallOut().length() > 10)
actCallOutDBValue = eventPostSchedules.getActCallOut().substring(10).trim();
else
actCallOutDBValue = eventPostSchedules.getActCallOut().trim();
}
callInDBValue = ((callInDBValue.trim().length() < 8) ? " ".concat(callInDBValue) : callInDBValue) + ((callOutDBValue.trim().equals("")) ? callOutDBValue : " - " + callOutDBValue);
position = new Label(eventPostSchedules.getPersonnelType());
name = new Label(eventPostSchedules.getName());
callInOutLabel = new Label(callInDBValue);
actualCallIn = new Label(actCallInDBValue);
actualCallIn.setFocusable(Boolean.TRUE);
actualCallIn.addPointerPressedListener(createActualCallChangeListener(actualCallIn, eventPostSchedules.getSerialId(), Constants.ACTUALCALLINFLAG, eventPostSchedules.getName(), eventPostSchedules.getActCallIn(), eventPostSchedules.getActCallOut(), eventPostSchedules.getActCallIn()));
actualCallOut = new Label(actCallOutDBValue);
actualCallOut.setFocusable(Boolean.TRUE);
actualCallOut.addPointerPressedListener(createActualCallChangeListener(actualCallOut, eventPostSchedules.getSerialId(), Constants.ACTUALCALLOUTFLAG, eventPostSchedules.getName(), eventPostSchedules.getActCallIn(), eventPostSchedules.getActCallOut(), eventPostSchedules.getActCallOut()));
agencyWorker = new TextField(eventPostSchedules.getAgencyWorker(), null, 5, TextArea.ANY);
position.setUIID("workersList");
name.setUIID("workersList");
callInOutLabel.setUIID("workersList");
actualCallIn.setUIID("workersListEditable");
actualCallOut.setUIID("workersListEditable");
agencyWorker.setUIID("workersListEditable");
workerBreak.setUIID("workersList");
if (Display.getInstance().isPortrait()) {
postSchedulesListContainer.addComponent(getTableConstraint(16, 8), position);
postSchedulesListContainer.addComponent(getTableConstraint(15, 8), name);
postSchedulesListContainer.addComponent(getTableConstraint(24, 8), callInOutLabel);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), actualCallIn);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), actualCallOut);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesListContainer.addComponent(getTableConstraint(6, 8), workerBreak);
} else {
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), position);
postSchedulesListContainer.addComponent(getTableConstraint(18, 10), name);
postSchedulesListContainer.addComponent(getTableConstraint(20, 10), callInOutLabel);
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), actualCallIn);
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), actualCallOut);
postSchedulesListContainer.addComponent(getTableConstraint(16, 10), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesListContainer.addComponent(getTableConstraint(7, 10), workerBreak);
}
}
postScheduleTableContainer.add(postSchedulesListContainer);
return postScheduleTableContainer;
}
}
}
public TableLayout.Constraint getTableConstraint(int widthPercent, int heightPercent) {
TableLayout.Constraint tableConstraint = new TableLayout.Constraint();
tableConstraint.setWidthPercentage(widthPercent);
tableConstraint.setHeightPercentage(heightPercent);
return tableConstraint;
}
}
Don't use flow layout for large dynamic data. You border layout with center constraint or absolute center.
Flow layout is overly simplistic and shouldn't be used for complex structures since Codename One doesn't reflow. There is a big discussion of that in the developer guide.

Data not set in excel

i have a piece of code to right into excel sheet,it is based on the row number and column name specified ,my issue is that if a column name is null then value will not set in the rest of the columns.
in this excel no value get added after Column 'D'
Below is my code
public boolean setExcelData(String sheetName, String colName, int rowNum, String data) throws AutoException {
dataFile();
try {
if (rowNum <= 0)
throw new AutoException(EXCEPTIION);
int index = wb.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
throw new AutoException(EXCEPTIION);
XSSFSheet sheet = wb.getSheetAt(index);
Row row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
System.out.println(row.getCell(i));
if (row.getCell(i) == null) {
throw new AutoException(EXCEPTIION);
} else if (row.getCell(i).getStringCellValue().trim().equals(colName)) {
colNum = i;
break;
}
}
if (colNum == -1)
throw new AutoException(EXCEPTIION);
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
Cell cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
FileOutputStream fileOut = new FileOutputStream(excelFilePath);
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
wb.close();
in.close();
} catch (Exception e) {
}
}
return true;
}
Any one can help me out.
thanks in advance
skip the for loop iteration if columnname is null
for (int i = 0; i < row.getLastCellNum(); i++) {
System.out.println(row.getCell(i));
if (String.IsNullOrEmpty(colName))
continue;
if (row.getCell(i) == null) {
throw new AutoException(EXCEPTIION);
} else if (row.getCell(i).getStringCellValue().trim().equals(colName)) {
colNum = i;
break;
}
}

Using Epplus to import data from an Excel file to SQL Server database table

I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

Resources