Spring MVCでExcelファイルをアップロードして表示する
1. 前書き
この記事では、Spring MVCフレームワークを使用してupload Excel files and display their content in a web pageを実行する方法を示します。
2. Excelファイルのアップロード
ファイルをアップロードできるようにするために、最初にMultipartFileを受け取り、それを現在の場所に保存するコントローラーマッピングを作成します。
private String fileLocation;
@PostMapping("/uploadExcelFile")
public String uploadFile(Model model, MultipartFile file) throws IOException {
InputStream in = file.getInputStream();
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + file.getOriginalFilename();
FileOutputStream f = new FileOutputStream(fileLocation);
int ch = 0;
while ((ch = in.read()) != -1) {
f.write(ch);
}
f.flush();
f.close();
model.addAttribute("message", "File: " + file.getOriginalFilename()
+ " has been uploaded successfully!");
return "excel";
}
次に、accept属性がExcelファイルのみを許可するように設定されたtype fileのinputを含むフォームでJSPファイルを作成しましょう。
3. Excelファイルを読む
アップロードされたExcelファイルを解析するために、.xlsファイルと.xlsxファイルの両方で機能するApache POIライブラリを使用します。
コンテンツと書式設定に関連するExcelセルのプロパティを含むMyCellというヘルパークラスを作成しましょう。
public class MyCell {
private String content;
private String textColor;
private String bgColor;
private String textSize;
private String textWeight;
public MyCell(String content) {
this.content = content;
}
//standard constructor, getters, setters
}
Excelファイルの内容をMyCellオブジェクトのリストを含むMapに読み込みます。
3.1. .xlsファイルの解析
A .xls file is represented in the Apache POI library by an HSSFWorkbookclass。これはHSSFSheetオブジェクトで構成されます。 .xlsファイルの内容を開いて読み取るには、Working with Microsoft Excel in Javaに関する記事を参照してください。
For parsing the formatting of a cell, we will obtain the HSSFCellStyleobject,は、背景色やフォントなどのプロパティを決定するのに役立ちます。 すべての読み取りプロパティは、MyCellオブジェクトの属性に設定されます。
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);
色はrgb(rVal, gVal, bVal)形式で読み取られるため、JSPページでCSSを使用して簡単に表示できます。
フォントのサイズ、太さ、色も取得しましょう。
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] + ")");
}
3.2. .xlsxファイルの解析
ブックの内容に関するFor files in the newer .xlsx format, we can use the XSSFWorkbook classおよび同様のもの。これもWorking with Microsoft Excel in Javaの記事に記載されています。
セルのフォーマットを.xlsxフォーマットで読み取る方法を詳しく見てみましょう。 まず、セルに関連付けられたwe will retrieve the XSSFCellStyle objectを使用して、背景色とフォントを決定します。
XSSFCellStyle cellStyle = cell.getCellStyle();
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();
この場合、色のRGB値はsigned byte値になるため、負の値に0xffを追加してunsigned値を取得します。
フォントのプロパティも決定しましょう。
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]) + ")");
}
3.3. 空の行の処理
The methods described above do not account for empty rows in an Excel file.空の行も表示するファイルの忠実な表現が必要な場合は、MyCellオブジェクトのArrayListを使用して結果のHashMapでこれらをシミュレートする必要があります。コンテンツとして空のStringsを含みます。
最初に、Excelファイルを読み取った後、ファイル内の空の行は、サイズが0のArrayListオブジェクトになります。
追加する必要のある空のStringオブジェクトの数を決定するために、最初にmaxNrCols変数を使用してExcelファイルの最長の行を決定します。 次に、その数の空のStringオブジェクトを、サイズが0のHashMap内のすべてのリストに追加します。
int maxNrCols = data.values().stream()
.mapToInt(List::size)
.max()
.orElse(0);
data.values().stream()
.filter(ls -> ls.size() < maxNrCols)
.forEach(ls -> {
IntStream.range(ls.size(), maxNrCols)
.forEach(i -> ls.add(new MyCell("")));
});
4. Excelファイルの表示
Spring MVCを使用して読み取られたExcelファイルを表示するには、コントローラーマッピングとJSPページを定義する必要があります。
4.1. Spring MVCコントローラー
上記のコードを呼び出してアップロードされたファイルのコンテンツを読み取る@RequestMappingメソッドを作成し、返されたMapをModel属性として追加しましょう。
@Resource(name = "excelPOIHelper")
private ExcelPOIHelper excelPOIHelper;
@RequestMapping(method = RequestMethod.GET, value = "/readPOI")
public String readPOI(Model model) throws IOException {
if (fileLocation != null) {
if (fileLocation.endsWith(".xlsx") || fileLocation.endsWith(".xls")) {
Map> data
= excelPOIHelper.readExcel(fileLocation);
model.addAttribute("data", data);
} else {
model.addAttribute("message", "Not a valid excel file!");
}
} else {
model.addAttribute("message", "File missing! Please upload an excel file.");
}
return "excel";
}
4.2. JSP
ファイルの内容を視覚的に表示するために、HTMLtableを作成し、各テーブルセルのstyle属性に、Excelファイルの各セルに対応する書式設定プロパティを追加します。 :
${cell.content}
5. 結論
この記事では、Excelファイルをアップロードし、Spring MVCフレームワークを使用してそれらをWebページに表示するためのサンプルプロジェクトを示しました。
完全なソースコードはGitHub projectにあります。