Image is not inserting in db from excel in java spring boot? - java

Hi Everyone I'm beginner in Java Spring Boot.I want to read the data from excel.Data contains both text and image.I have read text from excel and insert into db successfully.But I could not read the image and I have to insert the image into db.I have attached the error below Can anyone give me a solution? Any help would be appreciate.Thanks in advance....
Image :
#RequestMapping("uploadQuestion")
public String uploadQuestion(#RequestParam("file") MultipartFile file, #RequestParam Long examId, Model model,
HttpSession session) throws IOException, InvalidFormatException {
int flag = 0;
String id = (String) session.getAttribute("userId");
model.addAttribute("examList", onlineExamMasterRepository.findAll());
DataFormatter formatter = new DataFormatter();
List<OnlineExamQuestionMaster> quetions = new ArrayList<OnlineExamQuestionMaster>();
List<OnlineExamOptionMaster> options = new ArrayList<OnlineExamOptionMaster>();
if (file.isEmpty()) {
model.addAttribute("info", "Please select a file to upload");
return "onlinexam/questionUpload :: section";
}
InputStream in = file.getInputStream();
XSSFWorkbook workbook = new XSSFWorkbook(in);
XSSFSheet sheet = workbook.getSheetAt(0);
Row row;
System.out.println(sheet.getLastRowNum());
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
OnlineExamQuestionMaster qm = new OnlineExamQuestionMaster();
OnlineExamQuestionMasterPK qmp = new OnlineExamQuestionMasterPK();
OnlineExamOptionMasterPK omp[] = new OnlineExamOptionMasterPK[4];
OnlineExamOptionMaster om[] = new OnlineExamOptionMaster[4];
qmp.setExamId(examId);
qm.setLogTimestamp(new Date());
qm.setLogUserid(id);
flag++;
row = (Row) sheet.getRow(i);
System.out.println(row.getCell(0).toString());
if (row.getCell(0).toString().equals(null)) {
model.addAttribute("info", "Some columns are null please check and try");
return "onlinexam/questionUpload :: section";
} else {
qmp.setQuestionId(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
if (onlineExamQuestionMasterRepository.exists(qmp)) {
model.addAttribute("message", "Already QuestionId with " + formatter.formatCellValue(row.getCell(0))
+ " Exist for ExamId " + examId);
return "onlinexam/questionUpload :: section";
}
}
if (row.getCell(1).toString().equals("")) {
model.addAttribute("info", "Some columns are null please check and try");
return "onlinexam/questionUpload :: section";
} else
{
row = (Row) sheet.getRow(i);
Iterator<Cell> iterator2 = row.cellIterator();
/*XSSFWorkbook workbook2 = sheet.getWorkbook();
List<XSSFPictureData> pictures = workbook2.getAllPictures();
Iterator<XSSFPictureData> iterator = pictures.iterator();*/
while(iterator2.hasNext())
{
PictureData pictureData = (PictureData)iterator2.next();
String fileextension = pictureData.suggestFileExtension();
byte[] data = pictureData.getData();
if(fileextension.equals("jpeg"))
{
qm.setImage(data);;
}
else
qm.setQidDescription(row.getCell(1).toString().trim());
}
}
if (row.getCell(2).toString().equals("")) {
model.addAttribute("info", "Some columns are null please check and try");
return "onlinexam/questionUpload :: section";
} else {
omp[0] = new OnlineExamOptionMasterPK();
om[0] = new OnlineExamOptionMaster();
omp[0].setQid(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
omp[0].setOptionId("A");
omp[0].setExamId(examId);
om[0].setLogTimestamp(new Date());
om[0].setLogUserid(id);
om[0].setOptionDesc(row.getCell(2).toString().trim());
om[0].setId(omp[0]);
}
if (row.getCell(3).toString().equals("")) {
model.addAttribute("info", "Some columns are null please check and try");
return "onlinexam/questionUpload :: section";
} else {
omp[1] = new OnlineExamOptionMasterPK();
om[1] = new OnlineExamOptionMaster();
omp[1].setExamId(examId);
omp[1].setQid(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
omp[1].setOptionId("B");
om[0].setLogTimestamp(new Date());
om[0].setLogUserid(id);
om[1].setOptionDesc(row.getCell(3).toString().trim());
om[1].setId(omp[1]);
}
if (row.getCell(4).toString().equals("")) {
model.addAttribute("info", "Some columns are null please check and try");
return "onlinexam/questionUpload :: section";
} else {
omp[2] = new OnlineExamOptionMasterPK();
om[2] = new OnlineExamOptionMaster();
omp[2].setExamId(examId);
omp[2].setQid(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
omp[2].setOptionId("C");
om[0].setLogTimestamp(new Date());
om[0].setLogUserid(id);
om[2].setOptionDesc(row.getCell(4).toString().trim());
om[2].setId(omp[2]);
}
if (row.getCell(5).toString().equals("")) {
model.addAttribute("info", "Some columns are null please check and try");
return "onlinexam/questionUpload :: section";
} else {
omp[3] = new OnlineExamOptionMasterPK();
om[3] = new OnlineExamOptionMaster();
omp[3].setExamId(examId);
omp[3].setQid(Long.parseLong(formatter.formatCellValue(row.getCell(0))));
omp[3].setOptionId("D");
om[0].setLogTimestamp(new Date());
om[0].setLogUserid(id);
om[3].setOptionDesc(row.getCell(5).toString().trim());
om[3].setId(omp[3]);
}
if (row.getCell(6).toString().equals("")) {
model.addAttribute("info", "Some columns are null please check and try");
return "onlinexam/questionUpload :: section";
} else {
qm.setAnswer(row.getCell(6).toString().toUpperCase().trim());
}
if (row.getCell(7).toString().equals("")) {
model.addAttribute("info", "Some columns are null please check and try");
return "onlinexam/questionUpload :: section";
} else {
qm.setMarks(Long.parseLong(formatter.formatCellValue(row.getCell(7))));
}
qm.setId(qmp);
quetions.add(qm);
options.addAll(Arrays.asList(om));
}
for (OnlineExamQuestionMaster h : quetions) {
onlineExamQuestionMasterRepository.save(h);
}
System.out.println(options.size());
for (OnlineExamOptionMaster h : options) {
System.out.println(h.toString());
onlineExamOptionMasterRepository.save(h);
}
model.addAttribute("info", flag + "Questions Uploaded Sucessfully");
return "onlinexam/questionUpload :: section";
}
]3]3

Pictures are not cell content in Excel. They hover in a separate drawing layer (XSSFDrawing in case of XSSF) over the sheet and are anchored to cells.
So if the need is getting pictures according to the position they are anchored to, then we need to
get the drawing layer
loop over all shapes in that layer and if the shape is a picture, then
get the picture
get the anchor position of that picture
Following example is doing that and produces a Map which maps XSSFPicture to their positions. I have got the XSSFPicture because they provide much more information than the XSSFPictureData alone. And the XSSFPictureData can easily got form the XSSFPicture.
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.util.Map;
import java.util.HashMap;
public class ExcelGetPicturesWithPosition {
static Map<String, XSSFPicture> getPicturesWithPosition(XSSFSheet sheet) {
Map<String, XSSFPicture> pictures = new HashMap<String, XSSFPicture>();
XSSFDrawing drawing = sheet.getDrawingPatriarch();
for (XSSFShape shape : drawing.getShapes()) {
if (shape instanceof XSSFPicture) {
XSSFPicture picture = (XSSFPicture)shape;
XSSFClientAnchor anchor = picture.getClientAnchor();
String cellAddr = "R" + anchor.getRow1() + "C" + anchor.getCol1();
pictures.put(cellAddr, picture);
}
}
return pictures;
}
public static void main(String[] args) throws Exception {
XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("ExcelWithPictures.xlsx"));
XSSFSheet sheet = workbook.getSheetAt(0);
Map<String, XSSFPicture> pictures = getPicturesWithPosition(sheet);
System.out.println(pictures);
workbook.close();
}
}
Once having that Map it is easy to get the pictures while iterating the sheet. For example if we are on int row = 2; int column = 1;:
XSSFPicture picture = pictures.get("R"+row+"C"+column);

Related

extract full path for external references in a excel file

I am trying to get full path of external referenced files,
able to extract partial path not compete path for the exteranl referneced files.
With POI is it possible to achieve this. Or need to go with different library or approch?
try {
String filePath = "C:\\Users\\DATA\\2021 Plan Summary.xlsx";
Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath));
Map<String, String> dataMap = new HashMap<String, String>();
List<String> formulaList = new ArrayList<String>();
EvaluationWorkbook evalWorkbook = null;
if (workbook instanceof HSSFWorkbook) {
evalWorkbook = HSSFEvaluationWorkbook.create((HSSFWorkbook) workbook);
} else if (workbook instanceof XSSFWorkbook) {
evalWorkbook = XSSFEvaluationWorkbook.create((XSSFWorkbook) workbook);
}
List<ExternalLinksTable> externalLinksTableList = getReferencedWorkbooksXssfV2((XSSFWorkbook)workbook);
Sheet sheet = workbook.getSheetAt(0);
EvaluationSheet evalSheet = evalWorkbook.getSheet(0);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == CellType.FORMULA && cell.getCellFormula().contains("[")) {
// System.out.println(cell.getStringCellValue());
String cellFormula = cell.getCellFormula();
EvaluationCell evaluationCell = evalSheet.getCell(cell.getRowIndex(), cell.getColumnIndex());
Ptg[] formulaTokens = evalWorkbook.getFormulaTokens(evaluationCell);
for (Ptg formulaToken : formulaTokens) {
if (formulaToken instanceof Ref3DPxg) {
Ref3DPxg pxg = (Ref3DPxg) formulaToken;
int extWB = pxg.getExternalWorkbookNumber();
int extLink = extWB - 1;
ExternalLinksTable links = externalLinksTableList.get(extLink);
String filename = links.getLinkedFileName();
formulaList.add(cellFormula);
dataMap.put(StringUtils.substringBetween(cellFormula, "[", "]"), filename);
}
}
}
}
}
}
private static List<ExternalLinksTable> getReferencedWorkbooksXssfV2(XSSFWorkbook workbook) throws OpenXML4JException {
final List<ExternalLinksTable> externalLinksTable = workbook.getExternalLinksTable();
return externalLinksTable;
}

How to write data into multiple sheets in same excel [duplicate]

This question already has an answer here:
Creating multiple sheets using Apache poi and servlets
(1 answer)
Closed 1 year ago.
I am trying to write the data into same excel file in different sheets, below is the code I tried here only one sheet is creating and data is updating in that sheet, new sheet name is overriding on old sheet. Here I am calling call method two times with 2 different sheet name, when we call from 1st time data need to update in sheet1 and 2nd time call data need to update in sheet2 but in this code only sheet2 is creating and data updating in that.
public static void call(Map<String, String[]> dataListLMS_IPS, String sheet)
{
try {
String filePath = "C:\\Users\\PATIV25\\Downloads\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
FileOutputStream fileOut = new FileOutputStream(filename);
fileOut.close();
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(sheet);
XSSFRow row;
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
row = spreadsheet.createRow(rowid++);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
Cell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
// .xlsx is the format for Excel Sheets...
// writing the workbook into the file...
FileOutputStream out = new FileOutputStream(theDir);
workbook.write(out);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
call(data, "sheet1");
call(data, "sheet2");
}
The existing logic is incorrect. You need to separate the creation of file and sheets into different sections if you want to call the call method twice. Try this:
public static void call(Map<String, String[]> dataListLMS_IPS, FileOutputStream fileOut) throws IOException
{
XSSFWorkbook workbook = new XSSFWorkbook();
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
XSSFSheet spreadsheet = workbook.createSheet(key);
XSSFRow row;
row = spreadsheet.createRow(0);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
XSSFCell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
workbook.write(fileOut);
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
FileOutputStream fileOut = null;
try {
String filePath = "d:\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
fileOut = new FileOutputStream(filename);
call(data, fileOut);
call(data, fileOut);
}
catch (Exception e)
{
e.printStackTrace();
} finally {
if (fileOut != null)
fileOut.close();
}
}
It will create 2 sheets in the same Excel file.

Replace Data to word Document In Alfresco using java code excluding junk characters

I am doing Bulk Upload Task in Alfresco.
Before this i created custom action to call java code, i also successfully read data from excel sheet, and i found node reference of target document as well as source Document. Using that node reference i am also able to create new multiple Documents.
Now My requirement is, I want to replace Excel Data in that newly created Document. I tried to replace it, But It replacing the String only in First line of document, and it also deleting Rest of the existing contents inside newly created document. I have written Below code for this.
In below code i am first simply trying to replace some hard coded data to the Document.
But My requirement is i want to replace the data inside document which i already read from excel file.
Java Code:
public class MoveReplacedActionExecuter extends ActionExecuterAbstractBase {
InputStream is;
Cell cell = null;
public static final String NAME = "move-replaced";
private FileFolderService fileFolderService;
private NodeService nodeService;
private ContentService contentService;
private SearchService searchService;
#Override
protected void addParameterDefinitions(List < ParameterDefinition > paramList) {
}
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
try {
ContentReader contentReader = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT);
is = contentReader.getContentInputStream();
} catch (NullPointerException ne) {
System.out.println("Null Pointer Exception" + ne);
}
try {
Workbook workbook = new XSSFWorkbook(is);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator < Row > iterator = firstSheet.rowIterator();
while (iterator.hasNext()) {
ArrayList < String > al = new ArrayList < > ();
System.out.println("");
Row nextRow = iterator.next();
Iterator < Cell > cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print("\t" + cell.getStringCellValue());
al.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print("\t" + cell.getBooleanCellValue());
al.add(String.valueOf(cell.getBooleanCellValue()));
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print("\t" + cell.getNumericCellValue());
al.add(String.valueOf(cell.getNumericCellValue()));
break;
}
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
String query = "PATH:\"/app:company_home/cm:Dipak/cm:OfferLetterTemplate.doc\"";
SearchParameters sp = new SearchParameters();
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
sp.addStore(storeRef);
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
sp.setQuery(query);
ResultSet resultSet = searchService.query(sp);
System.out.println("Result Set" + resultSet.length());
NodeRef sourceNodeRef = null;
for (ResultSetRow row: resultSet) {
NodeRef currentNodeRef = row.getNodeRef();
sourceNodeRef = currentNodeRef;
System.out.println(currentNodeRef.toString());
}
NodeRef n = new NodeRef("workspace://SpacesStore/78342318-37b8-4b42-aadc-bb0ed5d413d9");
try {
org.alfresco.service.cmr.model.FileInfo fi = fileFolderService.copy(sourceNodeRef, n, "JustCreated" + Math.random() + ".doc");
NodeRef newNode = fi.getNodeRef();
QName TYPE_AUTHORTY = QName.createQName("sunpharma.hr.model", "hrdoctype");
nodeService.setType(newNode, TYPE_AUTHORTY);
ContentReader contentReader1 = contentService.getReader(newNode, ContentModel.PROP_CONTENT);
InputStream is2 = contentReader1.getContentInputStream();
POIFSFileSystem fs = new POIFSFileSystem(is2);
HWPFDocument doc = new HWPFDocument(fs);
doc = replaceText1(doc, "Company", "Datamatics");
ContentWriter writerDoc = contentService.getWriter(newNode, ContentModel.PROP_CONTENT, true);
writerDoc.putContent(doc.getDocumentText());
} catch (FileExistsException | FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static HWPFDocument replaceText1(HWPFDocument doc, String findText, String replaceText) {
System.out.println("In the method replacetext" + replaceText);
Range r1 = doc.getRange();
System.out.println("Range of Doc : " + r1);
for (int i = 0; i < r1.numSections(); ++i) {
Section s = r1.getSection(i);
for (int x = 0; x < s.numParagraphs(); x++) {
Paragraph p = s.getParagraph(x);
for (int z = 0; z < p.numCharacterRuns(); z++) {
CharacterRun run = p.getCharacterRun(z);
String text = run.text();
if (text.contains(findText)) {
run.replaceText(findText, replaceText);
} else {
System.out.println("NO text found");
}
}
}
}
return doc;
}
public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}
}
Its not possible to take direct file stream object in alfresco.
so i created one file at local drive, in background i performed all replacement operations. and after that i read all data using file input stream object. and later i used file that stream with node.
and it gave me my desired output. :)

Excel rows with multiple lines in one

I've created a Workbook to show an excel with different contents. That excel has some rows that contain some lines each. The problem is the excel only has that format when I click in a specific row and I want the entire excel looks like that.
This is my code:
Workbook worbook = new HSSFWorkbook();
Sheet sheet = worbook.createSheet("Publication List");
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Locale locale = resourceResponse.getLocale();
Font headerFont = worbook.createFont();
headerFont.setFontHeightInPoints((short) 11);
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
headerFont.setColor(new HSSFColor.DARK_BLUE().getIndex());
CellStyle headerStyle = worbook.createCellStyle();
headerStyle.setFont(headerFont);
headerStyle.setWrapText(true);
headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
headerStyle.setFillForegroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());
try {
List < Country > countries = CountryServiceUtil.getCountries();
if (allRequests != null) {
int columnHeader = 0;
Row rowHead = sheet.createRow(0);
for (String headerColumn: header) {
Cell cell = rowHead.createCell(columnHeader);
cell.setCellValue(LanguageUtil.get(locale, headerColumn));
cell.setCellStyle(headerStyle);
columnHeader++;
}
int requestRow = 1;
for (PublicationRequest publication: allRequests) {
Row rowsBody = sheet.createRow(requestRow);
Country country = CountryServiceUtil.fetchCountryByA2(publication.getCountry());
String fullAddress = publication.getAddress() + StringPool.RETURN_NEW_LINE + publication.getCp() + StringPool.SPACE + publication.getCity() + StringPool.RETURN_NEW_LINE + country.getName();
rowsBody.createCell(8).setCellValue(fullAddress);
//Publication items. Cell 8
long scopeGroupId = PortalUtil.getScopeGroupId(resourceRequest);
List < PublicationRequestItem > allRequestItems = PublicationRequestItemLocalServiceUtil.findBypublicationRequestId(publication.getPublicationRequestId());
String publicationsVocabulary = PrefsParamUtil.getString(resourceRequest.getPreferences(), resourceRequest, "publicationsVocabulary", "");
AssetVocabulary publicationsTypeVocabulary = null;
if (Validator.isNotNull(publicationsVocabulary)) {
try {
publicationsTypeVocabulary = AssetVocabularyLocalServiceUtil.getAssetVocabularyByUuidAndGroupId(publicationsVocabulary, scopeGroupId);
String category = StringPool.BLANK;
for (PublicationRequestItem item: allRequestItems) {
JournalArticle latestArticle;
latestArticle = JournalArticleLocalServiceUtil.getLatestArticle(scopeGroupId, item.getArticleId());
if (!category.equals(StringPool.BLANK)) {
category = category + StringPool.NEW_LINE;
}
category += RequestDisplayUtil.getPublicationTitle(locale, latestArticle, publicationsTypeVocabulary);
}
rowsBody.createCell(9).setCellValue(category);
} catch (PortalException e) {
e.printStackTrace();
}
}
requestRow++;
}
for (int column = 0; column < columnHeader + 1; column++) {
sheet.autoSizeColumn(column);
}
}
} catch (SystemException e) {
_log.error("Error while creating Excel file", e);
} catch (PortalException e1) {
e1.printStackTrace();
}
resourceResponse.setContentType("application/vnd.ms-excel");
resourceResponse.setProperty("expires", "-1d");
resourceResponse.setProperty("Pragma", "no-cache");
resourceResponse.setProperty(HttpHeaders.CACHE_CONTROL, "no-cache");
I've tried as well with char(10) but I get the same end
Thank you
Finally I got a solution.
I only was giving styles to the header cells:
for (String headerColumn: header) {
Cell cell = rowHead.createCell(columnHeader);
cell.setCellValue(LanguageUtil.get(locale, headerColumn));
cell.setCellStyle(headerStyle);
columnHeader++;
I had to create the body cells previously and give it some style:
rowsBody.createCell(8).getCellStyle().setWrapText(true);
rowsBody.getCell(8).setCellValue(fullAddress);

Passing multiple model in ModelAndView and Iterating those models

I have a requirement where I have to write HSSfWorkbook with multiple HSSfSheets.
For first sheet I have different columns and second sheet has different set of columns. For each sheet I have different stored procedure written.
Currently my java code is written in a way which can handle only one stored procedure data. I want to modify it and call second stored procedure to populate data in second sheet. I am setting the excel bean data in ModelAndView object and building the document. Now my question is how to fetch the each model and write it in HSSfSheet? Like in controller I am setting two beans in map downloadExcelBean and downloadExcelBean2. I want to write downloadExcelBean in first sheet and downloadExcelBean2 in second sheet. Please suggest.
My controller function is as below.
public ModelAndView exportToExcel(String fileName1, String filename2,String sheetname1,String sheetName2,
String[] headerLabels1, String[] headerLabels2,int[] datatypeArray1,int[] datatypeArray2, String procString1,String procString2,
Object[] objarray, HttpServletRequest arg0,
HttpServletResponse arg1, String[] dbColumnNameArray1,String[] dbColumnNameArray2)
throws Exception {
Log.info(DownloadExcelController.class,
"Execution Starts..exportExcel()");
Map<String, DownloadExcelBean> downloadExcelBean = new HashMap<String, DownloadExcelBean>();
//System.out.println(" in export excel part....."+procString+":::"+datatypeArray);
List<List> workLists1 = downloadExcelService.storedProcedureToExcel(
datatypeArray1, procString1, objarray, dbColumnNameArray1);
List<List> workLists2 = downloadExcelService.storedProcedureToExcel(
datatypeArray2, procString2, objarray, dbColumnNameArray2);
DownloadExcelBean bean = new DownloadExcelBean();
bean.setFilename(fileName1);
bean.setSheetname(sheetname1);
bean.setHeaderArray(headerLabels1);
bean.setDatatypeArray(datatypeArray1);
// bean.setVisibleArray(visibleArray);
bean.setData(workLists1);
DownloadExcelBean bean2 = new DownloadExcelBean();
bean2.setFilename(filename2);
bean2.setSheetname(sheetName2);
bean2.setHeaderArray(headerLabels2);
bean2.setDatatypeArray(datatypeArray2);
bean2.setData(workLists2);
downloadExcelBean.put("downloadExcelBean", bean);
downloadExcelBean.put("downloadExcelBean2", bean2);
return new ModelAndView("DownloadExcelView", "model",
downloadExcelBean);
}
And in DownloadExcelView.java I have build excel document function
protected void buildExcelDocument(Map model, HSSFWorkbook workbook,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Log.info(DownloadExcelView.class,
"Execution starts....buildExcelDocument()");
response.setHeader("Content-Type", "application/vnd.ms-excel");
Map<String, DownloadExcelBean> exceldownload = (Map<String, DownloadExcelBean>) model.get("model");
for (Map.Entry<String, DownloadExcelBean> mapobject : exceldownload.entrySet())
{
DownloadExcelBean obj = (DownloadExcelBean) mapobject.getValue();
String filename = obj.getFilename(); // File name
String sheetname = obj.getSheetname(); // sheet Name
String headerlist[] = obj.getHeaderArray(); // header names
int dataTypeArray[] = obj.getDatatypeArray();
List resultsetValues = obj.getData();
response.setHeader("Content-Disposition", "attachment; filename="
+ filename + ".xls");
HSSFSheet sheet = workbook.createSheet(sheetname); // create a sheet
HSSFSheet sheet1 = workbook.createSheet("Second tab");
HSSFCellStyle cellStyle = setHeaderStyle(workbook); // Apply bold
// for header
HSSFRow header = sheet1.createRow(0); // create a header row
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
short decimalDataformat = workbook.createDataFormat().getFormat(
"#,###,##0.00");
HSSFCellStyle decimalCellStyle = workbook.createCellStyle();
decimalCellStyle.setDataFormat(decimalDataformat);
HSSFCellStyle wrapStyle = workbook.createCellStyle();
wrapStyle.setWrapText(true);
int visibleCol = -1;
for (int i = 0; i < headerlist.length; i++) {
visibleCol++;
HSSFCell cell = header.createCell(visibleCol);
cell.setCellStyle(cellStyle);
cell.setCellValue(headerlist[i].replace("<br/>", ARConstants.EXPORT_CRLF));
}
// Excel cell values
HSSFRow hssfrow;
HSSFCell cell;
for (int row = 0; row < resultsetValues.size(); row++) {
List rowList = (ArrayList) resultsetValues.get(row);
hssfrow = sheet1.createRow(row + 1);
visibleCol = -1;
for (int col = 0; col < rowList.size(); col++) {
// if(visibleArray[col]){
visibleCol++;
cell = hssfrow.createCell(visibleCol);
if (dataTypeArray[col] == java.sql.Types.DECIMAL) {
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellStyle(decimalCellStyle);
if (rowList.get(col) != null)
cell.setCellValue((Double) rowList.get(col));
else
cell.setCellValue("");
} else if (dataTypeArray[col] == java.sql.Types.DATE) {
if (rowList.get(col) != null)
cell.setCellValue(dateFormat.format(rowList
.get(col)));
else
cell.setCellValue("");
}
else if (dataTypeArray[col] == java.sql.Types.TIMESTAMP) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellStyle(wrapStyle);
if (rowList.get(col) != null)
cell.setCellValue(StringUtils.dateToUSFormatDateTimeTillMins(rowList.get(col).toString())
.replace(" ", ARConstants.EXPORT_CRLF));
else
cell.setCellValue("");
}
else if (dataTypeArray[col] == java.sql.Types.OTHER)
{
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellStyle(wrapStyle);
String crlf = Character.toString((char) 13)
+ Character.toString((char) 10);
if (rowList.get(col) != null)
{
String str=(rowList.get(col).toString()).replaceAll("\t"," ");
if((str.replace("|", crlf)).length()> 32767)
cell.setCellValue((str.replace("|", crlf)).substring(0,32766));
else
cell.setCellValue(str.replace("|", crlf));
}
else
cell.setCellValue("");
}
else
{
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
if (rowList.get(col) != null)
{
String str=(rowList.get(col).toString()).replaceAll("\t"," ");
if(str.length() > 32767)
{
cell.setCellValue(str.substring(0,32766));
}
else
{
cell.setCellValue(str);
}
}
else
cell.setCellValue("");
}
// sheet.autoSizeColumn(col);
}
}
}
Log.info(DownloadExcelView.class,
"Execution ends....buildExcelDocument()");
}

Categories