序文
先週の勉強会で複数シートのエクスポートとインポートについて質問されたのですが、最初に思ったのは「easypoi には独自の方法があるのでは?」ということでした。
後から考えると、まだツールを探してデバッグしてコードを書いている段階で、jar パッケージの一部の機能に目を向けていない観客もいるかもしれません。
ということで、Excelのマルチシートテーブルのインポートとエクスポートについて書いていきます。
文章
興味のある方は、以前の Excel 関連の記事もお読みください。
最も単純な紹介記事:
EXCEL テーブルのエクスポートとデータのインポートを実現するための Springboot の MYSQL データの最も単純な組み合わせ - プログラマーが探した
また、単一の複数の Excel ファイルのエクスポートを作成し、ZIP パッケージに変換しました。
SpringBoot は複数の Excel ファイルをエクスポートし、ダウンロードのために .zip 形式に圧縮します - プログラマーが求めています
指定されたテンプレートのエクスポートもあります:
Springboot は Excel ファイルをエクスポートするためのカスタム テンプレートを指定します_Small Target Youth Blog-CSDN Blog_Custom Export Excel
この種の複合テーブルもあります:
Springboot インポートとエクスポート Excel、1 対多のリレーションシップ、複合テーブル、結合セル データ_springboot エクスポート Excel 結合セル_小規模ターゲット ユース ブログ - CSDN ブログ
次の動的エクスポートもあります。
Springboot では、何でもエクスポートできるユニバーサル エクスポート Excel ツールをパッケージ化しました。
さて、この記事に戻って始めましょう。
いつものように、まず今日 Excel のマルチシート テーブルのインポートとエクスポートを実現するためにどれだけのことを行う必要があるかを見てみましょう。
基本的に 0 に等しい、はい、特に書くことはありません。
1.pom.xml には依存関係が導入されています。
<!--easypoi-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.0.0</version>
</dependency>
2.yml設定:
server:
port: 8697
spring:
main:
allow-bean-definition-overriding: true
3. ツールクラス ExcelUtil.java (この記事で使用する関数のみを簡略化して保持)
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
public class ExcelUtil {
protected static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
private static final String XLS = "xls";
private static final String XLSX = "xlsx";
private static final String SPLIT = ".";
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
defaultExport(list, fileName, response);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcelMore(MultipartFile file, Class<T> pojoClass,ImportParams params){
if (file == null){
return null;
}
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
throw new RuntimeException("excel文件不能为空");
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return list;
}
public static Workbook getWorkbook(MultipartFile file) {
Workbook workbook=null;
try {
// 获取Excel后缀名
String fileName = file.getOriginalFilename();
if (StringUtils.isEmpty(fileName) || fileName.lastIndexOf(SPLIT) < 0) {
logger.warn("解析Excel失败,因为获取到的Excel文件名非法!");
return null;
}
String fileType = fileName.substring(fileName.lastIndexOf(SPLIT) + 1, fileName.length());
// 获取Excel工作簿
if (fileType.equalsIgnoreCase(XLS)) {
workbook = new HSSFWorkbook(file.getInputStream());
} else if (fileType.equalsIgnoreCase(XLSX)) {
workbook = new XSSFWorkbook(file.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
}
4. 使用するデータ クラス User.java をエクスポートおよびインポートします。
import cn.afterturn.easypoi.excel.annotation.Excel;
public class User {
@Excel(name = "学号", orderNum = "0")
private Integer id;
@Excel(name = "姓名", orderNum = "1")
private String userName;
@Excel(name = "年龄", orderNum = "2")
private String userAge;
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", userAge='" + userAge + '\'' +
'}';
}
public User() {
}
public User(Integer id, String userName, String userAge) {
this.id = id;
this.userName = userName;
this.userAge = userAge;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
}
5. テスト コントローラーを作成し、次のことを試します。
インターフェースは 2 つしかなく、インポートとエクスポートが 1 つずつあり、それらはすべてマルチシートです (実際、コードを理解していれば、マルチシートには単一シートが含まれることがわかります)。
まずインターフェースをエクスポートします。
@GetMapping("exportExcel")
public void exportExcel(HttpServletResponse response) {
List<User> userListOne = new ArrayList<>();
User user1 = new User();
user1.setId(1001);
user1.setUserName("JCccc");
user1.setUserAge("18");
userListOne.add(user1);
List<User> userListTwo = new ArrayList<>();
User user2 = new User();
user2.setId(2001);
user2.setUserName("Mike");
user2.setUserAge("18");
userListTwo.add(user2);
// 多个sheet配置参数
final List<Map<String, Object>> sheetsList = Lists.newArrayList();
final String sheetNameOne = "sheet1-1班";
Map<String, Object> exportMapOne = Maps.newHashMap();
final ExportParams exportParamsOne = new ExportParams(null, sheetNameOne, ExcelType.HSSF);
// 以下3个参数为API中写死的参数名 分别是sheet配置/导出类(注解定义)/数据集
exportMapOne.put("title", exportParamsOne);
exportMapOne.put("entity", User.class);
exportMapOne.put("data", userListOne);
final String sheetNameTwo = "sheet2-2班";
Map<String, Object> exportMapTwo = Maps.newHashMap();
final ExportParams exportParamsTwo = new ExportParams(null, sheetNameTwo, ExcelType.HSSF);
// 以下3个参数为API中写死的参数名 分别是sheet配置/导出类(注解定义)/数据集
exportMapTwo.put("title", exportParamsTwo);
exportMapTwo.put("entity", User.class);
exportMapTwo.put("data", userListTwo);
// 加入多sheet配置列表
sheetsList.add(exportMapOne);
sheetsList.add(exportMapTwo);
//导出操作
ExcelUtil.exportExcel(sheetsList, "userList.xls", response);
}
コード分析
:
インターフェイスを呼び出して効果を確認します。
ダウンロードした Excel ファイルを開くと、複数のシート データが期待どおりに表示されていることがわかります。
インポート インターフェイスをもう一度見てください。
@PostMapping("importExcel")
public void importExcel(@RequestParam("file") MultipartFile multipartFile) {
try {
//标题占几行
Integer titleRows = 0;
//表头占几行
Integer headerRows = 1;
Workbook workBook = ExcelUtil.getWorkbook(multipartFile);
//获取sheet数量
int sheetNum = workBook.getNumberOfSheets();
ImportParams params = new ImportParams();
//表头在第几行
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
for (int numSheet = 0; numSheet < sheetNum; numSheet++) {
String sheetName = workBook.getSheetAt(numSheet).getSheetName();
//第几个sheet页
params.setStartSheetIndex(numSheet);
List<User> result = ExcelUtil.importExcelMore(multipartFile, User.class, params);
System.out.println("sheetNum=" + numSheet + " sheetName=" + sheetName);
System.out.println("导入的数据=" + result.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
コード分析:
インポートされたデータのサンプル:
再生するには次のインターフェイスを呼び出します。
データが解析されて取得されたことがわかります。
さて、行きましょう。コピーして貼り付けるだけです。