excel winform 导入 导出_强大的 Excel 导入导出工具 hutool
“?最近項目上需要用到 Excel 的導入導出功能,想著之前使用的都有點麻煩,所以結合多方資料,終于找到了這個還算不錯的 Excel 處理工具,一起來看”
今日安利好物名為 Hutool-poi
Hutool-poi 是什么?
Java 針對MS Office的操作的庫屈指可數,比較有名的就是Apache的POI庫。這個庫異常強大,但是使用起來也并不容易。Hutool針對POI封裝一些常用工具,使Java操作Excel等文件變得異常簡單。
Hutool-poi是針對Apache POI的封裝,因此需要用戶自行引入POI庫,Hutool默認不引入。到目前為止,Hutool-poi支持:
Excel文件(xls, xlsx)的讀取(ExcelReader)
Excel文件(xls,xlsx)的寫出(ExcelWriter)
Hutool-poi 有什么作用?
Hutool-poi 包含了對 Excel 讀取和寫出的多種 API 封裝
ExcelUtil Excel工具類,讀取的快捷方法都被封裝于此
ExcelReader Excel讀取器,Excel讀取的封裝,可以直接構造后使用。
ExcelWriter Excel生成并寫出器,Excel寫出的封裝(寫出到流或者文件),可以直接構造后使用
Hutool-poi 能幫我干什么?
這里我們用 Hutool-poi 來簡單實現 Excel 的導入導出
01
—
引入相關依賴
引入?基礎相關依賴
? <dependency>??????<groupId>org.apache.poigroupId> <artifactId>poiartifactId> <version>3.17version>??dependency> <dependency> <groupId>org.apache.poigroupId> <artifactId>poi-ooxmlartifactId> <version>3.17version> dependency><dependency> <groupId>xercesgroupId>????<artifactId>xercesImplartifactId> <version>2.11.0version>dependency>02
—
實現 Excel 導入導出
1、FileUtil 類
package me.zhengjie.service.impl;import cn.hutool.core.io.IoUtil;import cn.hutool.core.util.IdUtil;import cn.hutool.poi.excel.BigExcelWriter;import cn.hutool.poi.excel.ExcelUtil;import cn.hutool.poi.excel.sax.handler.RowHandler;import com.alibaba.fastjson.JSONArray;import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.text.SimpleDateFormat;import java.util.*;/** * File工具類,擴展 hutool 工具包 * * @author Zheng Jie * @date 2018-12-27 */public class FileUtil extends cn.hutool.core.io.FileUtil { private static ListObject>> lineList = /** * 獲取文件擴展名,不帶 . */ public static String getExtensionName(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot > -1) && (dot < (filename.length() - 1))) { return filename.substring(dot + 1); } } return filename; } /** * Java文件操作 獲取不帶擴展名的文件名 */ public static String getFileNameNoEx(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot > -1) && (dot < (filename.length()))) { return filename.substring(0, dot); } } return filename; } /** * 將文件名解析成文件的上傳路徑 */ public static File upload(MultipartFile file, String filePath) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS"); String name = getFileNameNoEx(file.getOriginalFilename()); String suffix = getExtensionName(file.getOriginalFilename()); String nowStr = "-" + format.format(date); try { String fileName = name + nowStr + "." + suffix; String path = filePath + fileName; // getCanonicalFile 可解析正確各種路徑 File dest = new File(path).getCanonicalFile(); // 檢測是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } // 文件寫入 file.transferTo(dest); return dest; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 導出excel */ public static void downloadExcel(ListString, String tempPath = System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx"; File file = new File(tempPath); BigExcelWriter writer = ExcelUtil.getBigWriter(file); // 一次性寫出內容,使用默認樣式,強制輸出標題 writer.write(list, true); //response為HttpServletResponse對象 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); //test.xls是彈出下載對話框的文件名,不能為中文,中文請自行編碼 response.setHeader("Content-Disposition", "attachment;filename=file.xlsx"); ServletOutputStream out = response.getOutputStream(); // 終止后刪除臨時文件 file.deleteOnExit(); writer.flush(out, true); //此處記得關閉輸出Servlet流 IoUtil.close(out); } /** * excel導入工具類 * * @param file 文件 * @param columNames 列對應的字段名 * @return 返回數據集合 * @throws IOException */ public static ListString, FileInputStream inNew = new FileInputStream(file); if (file.getPath().endsWith(".xlsx")) { //讀取數據 ExcelUtil.read07BySax(file, 0, createRowHandler()); } if (file.getPath().endsWith(".xls")) { //讀取數據 ExcelUtil.read03BySax(file, 0, createRowHandler()); } //去除excel中的第一行數據 lineList.remove(0); //將數據封裝到list中 ListString, for (int i = 0; i < lineList.size(); i++) { if (null != lineList.get(i)) { Map<String, Object> hashMap = new HashMap<>(); for (int j = 0; j < columNames.length; j++) { Object property = lineList.get(i).get(j); hashMap.put(columNames[j], property); } dataList.add(hashMap); } else { break; } } return dataList; } /** * 通過實現handle方法編寫我們要對每行數據的操作方式 */ private static RowHandler createRowHandler() { //清空一下集合中的數據 lineList.removeAll(lineList); return new RowHandler() { @Override public void handle(int sheetIndex, int rowIndex, List rowlist) { //將讀取到的每一行數據放入到list集合中 JSONArray jsonObject = new JSONArray(rowlist); lineList.add(jsonObject.toJavaList(Object.class)); } }; }}2、導出
public void downloadTemplate(HttpServletResponse response) throws IOException { List> list = Lists.newArrayList(); Map map = Maps.newLinkedHashMap(); map.put("倉庫編號", "");????????map.put("倉庫名稱",?""); list.add(map); FileUtil.downloadExcel(list, response); }3、導入
public void uploadTemplate(HttpServletRequest request) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map fileMap = multipartRequest.getFileMap(); if (fileMap == null || fileMap.size() == 0) { System.out.println("請上傳文件,注意文件的name屬性為file"); } for (Map.Entry entry : fileMap.entrySet()) { MultipartFile multipartFile = entry.getValue(); // 4.獲取要保存的路徑文件夾 String property = request.getSession().getServletContext().getRealPath("/"); property = property.substring(0, property.length() - 5) + "/upload/"; File file = FileUtil.upload(multipartFile, property); List list = new ArrayList<>(); //list list.add("warehouseCode");????????????list.add("warehouseName");????????????// list 轉 string 數組 String[] str = list.toArray(new String[list.size()]); List> leading = FileUtil.leading(file, str); } }Hutool 中還有許多實用方法,感興趣的小伙伴可以多研究下哦
https://hutool.cn/docs/#/
總結
以上是生活随笔為你收集整理的excel winform 导入 导出_强大的 Excel 导入导出工具 hutool的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java创建对象new后面为啥可以传入参
- 下一篇: 程序异常是python语言基本控制结构_