* upload, read excel files with mvc

* formatting

* add excel files

* update excel files
This commit is contained in:
lor6 2017-02-17 17:06:34 +02:00 committed by KevinGilmore
parent 935b815ad4
commit 8fe5a2ac72
9 changed files with 254 additions and 300 deletions

BIN
spring-mvc-java/persons.xls Normal file

Binary file not shown.

Binary file not shown.

View File

@ -161,26 +161,11 @@
</dependency>
<!-- excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId>
<version>${jexcel.version}</version>
</dependency>
</dependencies>
@ -395,7 +380,6 @@
<!-- excel -->
<poi.version>3.16-beta1</poi.version>
<jexcel.version>1.0.6</jexcel.version>
</properties>
</project>

View File

@ -1,140 +1,188 @@
package com.baeldung.excel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ExcelPOIHelper {
public Map<Integer, ArrayList<String>> readExcel(String fileLocation) throws IOException {
public Map<Integer, List<MyCell>> readExcel(String fileLocation) throws IOException {
Map<Integer, ArrayList<String>> data = new HashMap<Integer, ArrayList<String>>();
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
int i = 0;
for (Row row : sheet) {
data.put(i, new ArrayList<String>());
for (Cell cell : row) {
switch (cell.getCellTypeEnum()) {
case STRING:
data.get(i)
.add(cell.getRichStringCellValue()
.getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
data.get(i)
.add(cell.getDateCellValue() + "");
} else {
data.get(i)
.add(cell.getNumericCellValue() + "");
}
break;
case BOOLEAN:
data.get(i)
.add(cell.getBooleanCellValue() + "");
break;
case FORMULA:
data.get(i)
.add(cell.getCellFormula() + "");
break;
default:
data.get(i)
.add(" ");
Map<Integer, List<MyCell>> data = new HashMap<>();
FileInputStream fis = new FileInputStream(new File(fileLocation));
if (fileLocation.endsWith(".xls")) {
data = readHSSFWorkbook(fis);
} else if (fileLocation.endsWith(".xlsx")) {
data = readXSSFWorkbook(fis);
}
int maxNrCols = 0;
for (List<MyCell> ls : data.values()) {
if (ls.size() > maxNrCols) {
maxNrCols = ls.size();
}
}
for (List<MyCell> ls : data.values()) {
if (ls.size() < maxNrCols) {
for (int i = ls.size(); i < maxNrCols; i++) {
ls.add(new MyCell(""));
}
}
i++;
}
if (workbook != null){
workbook.close();
return data;
}
private String readCellContent(Cell cell) {
String content = "";
switch (cell.getCellTypeEnum()) {
case STRING:
content = cell.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
content = cell.getDateCellValue() + "";
} else {
content = cell.getNumericCellValue() + "";
}
break;
case BOOLEAN:
content = cell.getBooleanCellValue() + "";
break;
case FORMULA:
content = cell.getCellFormula() + "";
break;
default:
content = "";
}
return content;
}
private Map<Integer, List<MyCell>> readHSSFWorkbook(FileInputStream fis) throws IOException {
Map<Integer, List<MyCell>> data = new HashMap<>();
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<MyCell>());
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
HSSFCell cell = row.getCell(j);
if (cell != null) {
HSSFCellStyle cellStyle = cell.getCellStyle();
MyCell myCell = new MyCell();
HSSFColor bgColor = cellStyle.getFillForegroundColorColor();
if (bgColor != null) {
short[] rgbColor = bgColor.getTriplet();
myCell.setBgColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")");
}
HSSFFont font = cell.getCellStyle()
.getFont(workbook);
myCell.setTextSize(font.getFontHeightInPoints() + "");
if (font.getBold()) {
myCell.setTextWeight("bold");
}
HSSFColor textColor = font.getHSSFColor(workbook);
if (textColor != null) {
short[] rgbColor = textColor.getTriplet();
myCell.setTextColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")");
}
myCell.setContent(readCellContent(cell));
data.get(i)
.add(myCell);
} else {
data.get(i)
.add(new MyCell(""));
}
}
}
}
} finally {
if (workbook != null) {
workbook.close();
}
}
return data;
}
public void writeExcel() throws IOException {
Workbook workbook = new XSSFWorkbook();
private Map<Integer, List<MyCell>> readXSSFWorkbook(FileInputStream fis) throws IOException {
XSSFWorkbook workbook = null;
Map<Integer, List<MyCell>> data = new HashMap<>();
try {
Sheet sheet = workbook.createSheet("Persons");
sheet.setColumnWidth(0, 6000);
sheet.setColumnWidth(1, 4000);
Row header = sheet.createRow(0);
workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
CellStyle headerStyle = workbook.createCellStyle();
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<MyCell>());
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
XSSFCell cell = row.getCell(j);
if (cell != null) {
XSSFCellStyle cellStyle = cell.getCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFFont font = ((XSSFWorkbook) workbook).createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 16);
font.setBold(true);
headerStyle.setFont(font);
Cell headerCell = header.createCell(0);
headerCell.setCellValue("Name");
headerCell.setCellStyle(headerStyle);
headerCell = header.createCell(1);
headerCell.setCellValue("Age");
headerCell.setCellStyle(headerStyle);
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
Row row = sheet.createRow(2);
Cell cell = row.createCell(0);
cell.setCellValue("John Smith");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue(20);
cell.setCellStyle(style);
row = sheet.createRow(3);
cell = row.createCell(0);
cell.setCellValue("Ana Johnson");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue(30);
cell.setCellStyle(style);
File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx";
FileOutputStream outputStream = new FileOutputStream(fileLocation);
workbook.write(outputStream);
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
MyCell myCell = new MyCell();
XSSFColor bgColor = cellStyle.getFillForegroundColorColor();
if (bgColor != null) {
byte[] rgbColor = bgColor.getRGB();
myCell.setBgColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")");
}
XSSFFont font = cellStyle.getFont();
myCell.setTextSize(font.getFontHeightInPoints() + "");
if (font.getBold()) {
myCell.setTextWeight("bold");
}
XSSFColor textColor = font.getXSSFColor();
if (textColor != null) {
byte[] rgbColor = textColor.getRGB();
myCell.setTextColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")");
}
myCell.setContent(readCellContent(cell));
data.get(i)
.add(myCell);
} else {
data.get(i)
.add(new MyCell(""));
}
}
}
}
} finally {
if (workbook != null) {
workbook.close();
}
}
return data;
}
}

View File

@ -1,82 +0,0 @@
package com.baeldung.excel;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.Number;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@Service
public class JExcelHelper {
public Map<Integer, ArrayList<String>> readJExcel(String fileLocation) throws IOException, BiffException {
Map<Integer, ArrayList<String>> data = new HashMap<>();
Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
Sheet sheet = workbook.getSheet(0);
int rows = sheet.getRows();
int columns = sheet.getColumns();
for (int i = 0; i < rows; i++) {
data.put(i, new ArrayList<>());
for (int j = 0; j < columns; j++) {
data.get(i).add(sheet.getCell(j, i).getContents());
}
}
return data;
}
public void writeJExcel() throws IOException, WriteException {
WritableWorkbook workbook = null;
try {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xls";
workbook = Workbook.createWorkbook(new File(fileLocation));
WritableSheet sheet = workbook.createSheet("Sheet 1", 0);
WritableCellFormat headerFormat = new WritableCellFormat();
WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
headerFormat.setFont(font);
headerFormat.setBackground(Colour.LIGHT_BLUE);
headerFormat.setWrap(true);
Label headerLabel = new Label(0, 0, "Name", headerFormat);
sheet.setColumnView(0, 60);
sheet.addCell(headerLabel);
headerLabel = new Label(1, 0, "Age", headerFormat);
sheet.setColumnView(0, 40);
sheet.addCell(headerLabel);
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setWrap(true);
Label cellLabel = new Label(0, 2, "John Smith", cellFormat);
sheet.addCell(cellLabel);
Number cellNumber = new Number(1, 2, 20, cellFormat);
sheet.addCell(cellNumber);
cellLabel = new Label(0, 3, "Ana Johnson", cellFormat);
sheet.addCell(cellLabel);
cellNumber = new Number(1, 3, 30, cellFormat);
sheet.addCell(cellNumber);
workbook.write();
} finally {
if (workbook != null) {
workbook.close();
}
}
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.excel;
public class MyCell {
private String content;
private String textColor;
private String bgColor;
private String textSize;
private String textWeight;
public MyCell() {
}
public MyCell(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTextColor() {
return textColor;
}
public void setTextColor(String textColor) {
this.textColor = textColor;
}
public String getBgColor() {
return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public String getTextSize() {
return textSize;
}
public void setTextSize(String textSize) {
this.textSize = textSize;
}
public String getTextWeight() {
return textWeight;
}
public void setTextWeight(String textWeight) {
this.textWeight = textWeight;
}
}

View File

@ -108,11 +108,6 @@ public class WebConfig extends WebMvcConfigurerAdapter {
configurer.setUrlPathHelper(urlPathHelper);
}
@Bean
public JExcelHelper jExcelHelper() {
return new JExcelHelper();
}
@Bean
public ExcelPOIHelper excelPOIHelper() {
return new ExcelPOIHelper();

View File

@ -10,20 +10,15 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.baeldung.excel.*;
import jxl.read.biff.BiffException;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import jxl.write.WriteException;
@Controller
public class ExcelController {
private String fileLocation;
@Resource(name = "jExcelHelper")
private JExcelHelper jExcelHelper;
@Resource(name = "excelPOIHelper")
private ExcelPOIHelper excelPOIHelper;
@ -45,36 +40,19 @@ public class ExcelController {
}
f.flush();
f.close();
System.out.println(fileLocation);
model.addAttribute("message", "File: " + file.getOriginalFilename() + " has been uploaded successfully!");
return "excel";
}
@RequestMapping(method = RequestMethod.GET, value = "/readJExcel")
public String readJExcel(Model model) throws IOException, BiffException {
if (fileLocation != null) {
if (fileLocation.endsWith(".xls")) {
Map<Integer, ArrayList<String>> data = jExcelHelper.readJExcel(fileLocation);
model.addAttribute("data", data);
} else {
model.addAttribute("message", "Not a valid .xls file!");
}
} else {
model.addAttribute("message", "File missing! Please upload an excel file.");
}
return "excel";
}
@RequestMapping(method = RequestMethod.GET, value = "/readPOI")
public String readPOI(Model model) throws IOException {
if (fileLocation != null) {
if (fileLocation.endsWith(".xlsx")) {
Map<Integer, ArrayList<String>> data = excelPOIHelper.readExcel(fileLocation);
if (fileLocation.endsWith(".xlsx") || fileLocation.endsWith(".xls")) {
Map<Integer, List<MyCell>> data = excelPOIHelper.readExcel(fileLocation);
model.addAttribute("data", data);
} else {
model.addAttribute("message", "Not a valid .xlsx file!");
model.addAttribute("message", "Not a valid excel file!");
}
} else {
model.addAttribute("message", "File missing! Please upload an excel file.");
@ -82,24 +60,4 @@ public class ExcelController {
return "excel";
}
@RequestMapping(method = RequestMethod.POST, value = "/writeJExcel")
public String writeJExcel(Model model) throws IOException, BiffException, WriteException {
jExcelHelper.writeJExcel();
model.addAttribute("message", "Write successful!");
return "excel";
}
@RequestMapping(method = RequestMethod.POST, value = "/writePOI")
public String writePOI(Model model) throws IOException {
excelPOIHelper.writeExcel();
model.addAttribute("message", "Write successful!");
return "excel";
}
}

View File

@ -1,6 +1,6 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
@ -8,49 +8,43 @@
<title>Excel Processing</title>
</head>
<body>
<c:url value="/uploadExcelFile" var="uploadFileUrl" />
<c:url value="/excelProcessing" var="resetUrl" />
<c:url value="/readJExcel" var="readJExcelUrl" />
<c:url value="/writeJExcel" var="writeJExcelUrl" />
<c:url value="/readPOI" var="readPOIUrl" />
<c:url value="/writePOI" var="writePOIUrl" />
<c:url value="/uploadExcelFile" var="uploadFileUrl" />
<c:url value="/excelProcessing" var="resetUrl" />
<c:url value="/readPOI" var="readPOIUrl" />
<form method="post" enctype="multipart/form-data" action="${uploadFileUrl}" >
<input type="file" name="file" accept=".xls,.xlsx"/>
<input type="submit" value="Upload file"/>
</form>
<br />
${message }
<br /> <br />
<form method="GET" action="${resetUrl}" >
<input type="submit" value="Reset" />
</form>
<br /> <br />
<a href="${readJExcelUrl}">Read file using JExcel</a> &nbsp;&nbsp;&nbsp;
<a href="${readPOIUrl}">Read file using Apache POI</a>
<br /> <br />
<form method="post" enctype="multipart/form-data" action="${uploadFileUrl}">
<input type="file" name="file" accept=".xls,.xlsx" />
<input type="submit" value="Upload file" />
</form>
<br />
<form method="GET" action="${resetUrl}">
<input type="submit" value="Reset" />
</form>
<br /> ${message }
<br />
<br />
File content:
<c:if test="${not empty data}">
<table style="border:1px solid black;border-collapse:collapse;">
<c:forEach items="${data}" var="row">
<tr>
<c:forEach items="${row.value}" var="cell">
<td style="border:1px solid black">${cell}</td>
</c:forEach>
</tr>
</c:forEach>
</table>
</c:if>
<br /> <br />
<form action="${writeJExcelUrl}" method="POST">
<input type="submit" value="Write to file using JExcel" />
</form>
<br />
<form action="${writePOIUrl}" method="POST">
<input type="submit" value="Write to file using Apache POI" />
</form>
<form action="${readPOIUrl }">
<input type="submit" value="Display file content" />
</form>
<br />
<br />
<c:if test="${not empty data}">
<table style="border: 1px solid black; border-collapse: collapse;">
<c:forEach items="${data}" var="row">
<tr>
<c:forEach items="${row.value}" var="cell">
<td style="border:1px solid black;height:20px;width:100px;
background-color:${cell.bgColor};color:${cell.textColor};
font-weight:${cell.textWeight};font-size:${cell.textSize}pt;">
${cell.content}
</td>
</c:forEach>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>