Monday, October 16, 2017

Excel

http://javasampleapproach.com/java-integration/upload-multipartfile-spring-boot


package com.javasampleapproach.uploadfile;

import javax.annotation.Resource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.javasampleapproach.uploadfile.storage.StorageService;

@SpringBootApplication
public class SpringBootUploadFileApplication implements CommandLineRunner{

@Resource
StorageService storageService;
public static void main(String[] args) {
SpringApplication.run(SpringBootUploadFileApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}

}


package com.javasampleapproach.uploadfile.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import com.javasampleapproach.uploadfile.storage.StorageService;

@Controller
public class UploadController {

@Autowired
StorageService storageService;

List<String> files = new ArrayList<String>();

@GetMapping("/")
public String listUploadedFiles(Model model) {
return "uploadForm";
}

@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
try {
storageService.store(file);
model.addAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
files.add(file.getOriginalFilename());
} catch (Exception e) {
model.addAttribute("message", "FAIL to upload " + file.getOriginalFilename() + "!");
}
return "uploadForm";
}

@GetMapping("/gellallfiles")
public String getListFiles(Model model) {
model.addAttribute("files",
files.stream()
.map(fileName -> MvcUriComponentsBuilder
.fromMethodName(UploadController.class, "getFile", fileName).build().toString())
.collect(Collectors.toList()));
model.addAttribute("totalFiles", "TotalFiles: " + files.size());
return "listFiles";
}

@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
Resource file = storageService.loadFile(filename);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
}




package com.javasampleapproach.uploadfile.storage;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;


@Service
public class StorageService {

Logger log = LoggerFactory.getLogger(this.getClass().getName());
private final Path rootLocation = Paths.get("upload-dir");

public void store(MultipartFile file){
try {
            Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
        } catch (Exception e) {
        throw new RuntimeException("FAIL!");
        }
}

    public Resource loadFile(String filename) {
        try {
            Path file = rootLocation.resolve(filename);
            Resource resource = new UrlResource(file.toUri());
            if(resource.exists() || resource.isReadable()) {
                return resource;
            }else{
            throw new RuntimeException("FAIL!");
            }
        } catch (MalformedURLException e) {
        throw new RuntimeException("FAIL!");
        }
    }
 
    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    public void init() {
        try {
            Files.createDirectory(rootLocation);
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize storage!");
        }
    }
}



<html xmlns:th="http://www.thymeleaf.org">
<body>
<h2>List All Uploaded Files</h2>
<div>
<ul>
<li th:each="file : ${files}">
<a th:href="${file}" th:text="${file}" />
</li>
</ul>
</div>
<div>
<h3 th:text="${totalFiles}"/>
<a href="/">Back to UploadForm!</a>
</div>
</body>

</html>


<html xmlns:th="http://www.thymeleaf.org">
<body>

<div th:if="${message}">
<h2 th:text="${message}"/>
</div>

<div>
<form method="POST" enctype="multipart/form-data" action="/">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
</div>
<a href="/gellallfiles">Get List Files</a>
</body>
</html>

spring.http.multipart.max-file-size=500KB
spring.http.multipart.max-request-size=500KB


package com.javasampleapproach.uploadfile;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootUploadFileApplicationTests {

@Test
public void contextLoads() {
}

}


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.javasampleapproach.uploadfile</groupId>
<artifactId>SpringBootUploadFile</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>

<name>SpringBootUploadFile</name>
<description>SpringBootUploadFile</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>






























dd following jar files:
  • poi-3.9.jar 
  • poi-ooxml-3.9.jar 
  • poi-ooxml-schemas-3.7.jar 
  • xmlbeans-2.3.0.jar 
  • dom4j-1.6.1.jar

package com.excel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcel {
public static void readXLSFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xls");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row
HSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(HSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(HSSFCell) cells.next();
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
// public static void writeXLSFile() throws IOException {
// String excelFileName = "C:/Test.xls";//name of excel file
// String sheetName = "Sheet1";//name of sheet
// HSSFWorkbook wb = new HSSFWorkbook();
// HSSFSheet sheet = wb.createSheet(sheetName) ;
// //iterating r number of rows
// for (int r=0;r < 5; r++ )
// {
// HSSFRow row = sheet.createRow(r);
// //iterating c number of columns
// for (int c=0;c < 5; c++ )
// {
// HSSFCell cell = row.createCell(c);
// cell.setCellValue("Cell "+r+" "+c);
// }
// }
// FileOutputStream fileOut = new FileOutputStream(excelFileName);
// //write this workbook to an Outputstream.
// wb.write(fileOut);
// fileOut.flush();
// fileOut.close();
// }
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("/Users/tusharsaran/Documents/excel.xlsx");
XSSFWorkbook  wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook(); 
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
/*public static void writeXLSXFile() throws IOException {
String excelFileName = "C:/Test.xlsx";//name of excel file
String sheetName = "Sheet1";//name of sheet
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName) ;
//iterating r number of rows
for (int r=0;r < 5; r++ )
{
XSSFRow row = sheet.createRow(r);
//iterating c number of columns
for (int c=0;c < 5; c++ )
{
XSSFCell cell = row.createCell(c);
cell.setCellValue("Cell "+r+" "+c);
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}*/
public static void main(String[] args) throws IOException {
//writeXLSFile();
//readXLSFile();
//writeXLSXFile();
readXLSXFile();
}
}















Note: .xlsx Which will accommodate more number of rows(maximum 1,048,576). Usually in .xls format which will throw java heap space problem, can’t create more than 65,000 rows.


Reading Excel file data and making java objects Example by using POI-API


ExcelReader.java
===============================================

import java.math.BigDecimal;

import java.util.List;

import java.util.Map;

import java.util.ArrayList;

import java.util.HashMap;

import java.io.FileInputStream;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.xyz.vo.CourseVo;

public class ExcelReader {

    private static final Logger LOG = LoggerFactory.getLogger(ExcelReader.class);

    public List<CourseVo> readDataFromExcel(String filePath){

        Map<String,Object> map = readExcelSheet(filePath);

        LOG.info((String)map.get("headers"));

        List<CourseVo> valueObjectList = (List<CourseVo>)map.get("valueObjectList");

        for (CourseVo vo:valueObjectList) {
            LOG.info("Code :  " + vo.getCode()+"  Name: "+vo.getName()+"  Sessions : "+vo.getSessions()+
                    "  Duration : "+vo.getDuration()+"  MaxScoreMarks : "+vo.getScoreMarks()+" StartMonth  : "+vo.getStartMonth());

        }

        return volist;

    }

  

    public Map<String,Object> readExcelSheet(String filePath) {

      

            CourseVo courseVo = null;

            Map<String, Object> courseVOMap = null;

            try {

                LOG.info("File path"+filePath);

                XSSFWorkbook myWorkBook = new XSSFWorkbook(new FileInputStream(filePath));

                XSSFSheet mySheet = myWorkBook.getSheetAt(0);

                boolean isFirstRow = true;

                courseVOMap = new HashMap<String, Object>();

                List<CourseVo> cellsList = new ArrayList<CourseVo>();

                String headers = null;

                for(Row myRow : mySheet){

                    courseVo = new CourseVo();

                    if (isFirstRow) {

                        headers = addHeaderRowCells(courseVo, myRow);

                        courseVOMap.put("headers", headers);

                    } else {

                        addVoRowCells(cellsList, myRow);

                    }

                  

                    if(isFirstRow) {

                        isFirstRow = false;

                    }

                }

                courseVOMap.put("valueObjectList", cellsList);

            } catch (Exception e) {

                LOG.error(e.getMessage());

            }

            return courseVOMap;

        }

    public void addVoRowCells(List<CourseVo> cellList, Row row) {

        int cellInd = 0;

        CourseVo valueObject = new CourseVo();

      

        Cell cell = row.getCell(cellInd++);

            try{

            valueObject.setCode(String.valueOf((int)cell.getNumericCellValue()));

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setName(cell.getStringCellValue());

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setSessions((short)cell.getNumericCellValue());

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setDuration(BigDecimal.valueOf(cell.getNumericCellValue()));

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setScoreMarks(BigDecimal.valueOf((int)cell.getNumericCellValue()));

            }catch(Exception e){

                LOG.error(e.getMessage());

            }

            myCell = row.getCell(cellInd++);

            try{

            valueObject.setStartMonth(cell.getDateCellValue());

            }catch(Exception e){

                LOG.error(e.getMessage(););

            }

            cellList.add(valueObject);
}

  

    public String addHeaderRowCells(CourseVo vo, Row row) {

        int cellInd = 0;

        String header = "";

        try{

            Cell cell = row.getCell(cellInd++);

            header = cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

            cell = row.getCell(cellInd++);

            header += "," + cell.getStringCellValue();

        }catch(Exception e){

            LOG.error(e.getMessage(););

        }

        return header;

    }

    }

CourseVo.java
========================================
package com.xyz.vo;

import java.math.BigDecimal;

import java.util.Date;

/**

 * @author Pedababu M

 *

 */

public class CourseVo {

    String code;

    String name;

    short sessions;

    BigDecimal Duration;

    BigDecimal scoreMarks;

    Date startMonth;

    /**

     * @return the code

     */

    public String getCode() {

        return code;

    }

    /**

     * @param code the code to set

     */

    public void setCode(String code) {

        this.code = code;

    }

    /**

     * @return the name

     */

    public String getName() {

        return name;

    }

    /**

     * @param name the name to set

     */

    public void setName(String name) {

        this.name = name;

    }

    /**

     * @return the sessions

     */

    public short getSessions() {

        return sessions;

    }

    /**

     * @param sessions the sessions to set

     */

    public void setSessions(short sessions) {

        this.sessions = sessions;

    }

    /**

     * @return the duration

     */

    public BigDecimal getDuration() {

        return Duration;

    }

    /**

     * @param duration the duration to set

     */

    public void setDuration(BigDecimal duration) {

        Duration = duration;

    }

    /**

     * @return the scoreMarks

     */

    public BigDecimal getScoreMarks() {

        return scoreMarks;

    }

    /**

     * @param scoreMarks the scoreMarks to set

     */

    public void setScoreMarks(BigDecimal scoreMarks) {

        this.scoreMarks = scoreMarks;

    }

    /**

     * @return the startMonth

     */

    public Date getStartMonth() {

        return startMonth;

    }

    /**

     * @param startMonth the startMonth to set

     */

    public void setStartMonth(Date startMonth) {

        this.startMonth = startMonth;

    }

}

No comments:

Post a Comment