excel匯入與匯出
阿新 • • 發佈:2020-10-22
Excel生成
匯入依賴
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.15</version> </dependency>
<!--easypoi--><dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-web</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-annotation</artifactId> <version>3.2.0</version> </dependency>
控制層程式碼:
@PostMapping("/tcontrolEntmeasuresExcel") private void TControlEntmeasuresExcel(HttpServletResponse response, HttpServletRequest request){ String[] fieldData = new String[] {"序號", "企業名稱", "行業", "設施名稱", "年份"};
//查詢資料庫得到想要匯出資料的list集合 List<TControlEntmeasures> findT_control_entmeasuresByallexcel = tcontrolEntmeasuresService.findT_control_entmeasuresByallexcel(); controlReserveplanService.comCompanyExcelXLSX(response, request,fieldData); }
業務層controlReserveplanService.comCompanyExcelXLSX(response, request,fieldData程式碼
public void comCompanyExcelXLSX(HttpServletResponse response, List<TControlEntmeasures> list, String startTime, String endTime, String[] fieldData) { int cowspan = 0; if(fieldData != null) { cowspan = fieldData.length; } try { String fileName = "汙染源管控措施"; response.setContentType("application/vnd.ms-excel"); // 傳遞中文引數編碼 String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8"); response.setHeader("content-disposition", ";filename="+codedFileName+".xlsx"); /** * 建立工作表 */ XSSFWorkbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("0"); //設定列寬 sheet.setColumnWidth(0, 256*10); sheet.setColumnWidth(1, 256*20); sheet.setColumnWidth(2, 256*40); sheet.setColumnWidth(3, 256*20); sheet.setColumnWidth(4, 256*25); sheet.setColumnWidth(5, 256*25); sheet.setColumnWidth(6, 256*25); sheet.setColumnWidth(7, 256*25); sheet.setColumnWidth(8, 256*25); sheet.setColumnWidth(9, 256*15); sheet.setColumnWidth(10, 256*15); sheet.setColumnWidth(11, 256*20); sheet.setColumnWidth(12, 256*15); sheet.setColumnWidth(13, 256*15); sheet.setColumnWidth(14, 256*15); sheet.setColumnWidth(15, 256*15); /** * 標題樣式 樣式 */ CellStyle titleCellStyle = wb.createCellStyle(); titleCellStyle.setBorderLeft(BorderStyle.NONE); titleCellStyle.setBorderRight(BorderStyle.NONE); titleCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中 titleCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中 XSSFFont titleFont = wb.createFont(); titleFont.setFontHeight(18); titleFont.setBold(true); titleCellStyle.setFont(titleFont); /** * 主標題 在這裡插入主標題 */ Row titleRow; Cell titleCell; sheet.addMergedRegion(new CellRangeAddress((short) 0, (short) 0, (short) 0, (short) cowspan));//合併單元格;四個引數分別為起始行、終止行、起始列、終止列 titleRow = sheet.createRow(0);//從0開始,第一行 for (int j = 0; j < 3; j++) { titleCell = titleRow.createCell(j); titleCell.setCellType(CellType.STRING); titleCell.setCellStyle(titleCellStyle); titleCell.setCellValue("汙染源管控措施"); } /** * 時間範圍 */ CellStyle timeCellStyle = wb.createCellStyle(); timeCellStyle.setBorderLeft(BorderStyle.NONE); timeCellStyle.setBorderRight(BorderStyle.NONE); timeCellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 水平居中 timeCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中 XSSFFont timeFont = wb.createFont(); timeFont.setFontHeight(12); timeCellStyle.setFont(timeFont); /** * 列 標題 在這裡插入標題 */ CellStyle textCellStyle = wb.createCellStyle(); textCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中 textCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中 XSSFFont textFont = wb.createFont(); textFont.setFontHeight(12); textFont.setBold(true); textCellStyle.setFont(textFont); //列標題賦值處理 Row rowLabel; Cell cellLabel; rowLabel = sheet.createRow(1);//第二行,插入標題 for (int j = 0; j < fieldData.length; j++) { cellLabel = rowLabel.createCell(j); cellLabel.setCellType(CellType.STRING); cellLabel.setCellStyle(textCellStyle); cellLabel.setCellValue(fieldData[j]); } /** * 單元格 樣式 */ CellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中 cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 上下居中 /** * --列 資料 在這裡插入資料 */ int i=2; int count = 2;//第三行;插入資料 Row rowCheck; for (TControlEntmeasures temp : list) { rowCheck = sheet.createRow(count); rowCheck.setRowStyle(cellStyle); rowCheck.createCell(0).setCellValue(i-1); rowCheck.createCell(1).setCellValue(temp.getEntName());//企業名稱 rowCheck.createCell(2).setCellValue(temp.getRedalert());//紅色預警等級 rowCheck.createCell(3).setCellValue(temp.getRedwarningscheme());//紅色措施 ...
...
...
rowCheck.createCell(15).setCellValue(temp.getYear());//年份 for(int n=0; n<15; n++) { rowCheck.getCell(n).setCellStyle(cellStyle);//給單元格加上樣式 } count++;//迴圈一次行數+1 i++;//迴圈一次序號+1 } /** * 頁尾 */ wb.setSheetName(0, "汙染源管控措施"); /** * 進行匯出 */ OutputStream out = response.getOutputStream(); wb.write(out); out.flush(); out.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
Excel匯入資料庫
控制層程式碼:
/** * 根據檔案路徑匯入excel資料 * @param response */ @PostMapping("/tcontrolEntmeasuresExcelImport") private void TControlEntmeasuresExcelImport(HttpServletResponse response){//傳入對應需要匯入文件的路徑和建立的實體類 List<TControlEntmeasuresExcel> tcontrolEntmeasuresExcellmport = ExcelUtiles.importExcel("F:\\程式快捷\\---文件\\--模板.xlsx", 0, 1, TControlEntmeasuresExcel.class); for(int i=0;i<tcontrolEntmeasuresExcellmport.size();i++) { TControlEntmeasuresExcel tControlEntmeasuresExcel = tcontrolEntmeasuresExcellmport.get(i); String entId = tControlEntmeasuresExcel.getEntId();//獲取企業名稱進行查詢企業id插入 String deviceId = tControlEntmeasuresExcel.getDeviceId();//獲取設施名稱查詢設施id插入 String redStart = tControlEntmeasuresExcel.getRedStart();//獲取是否啟動紅色預警 ...
...
...
TControlEntmeasures controlEntmeasures =new TControlEntmeasures();
controlEntmeasures.setYear(Integer.valueOf(tControlEntmeasuresExcel.getYear()));//年份
controlEntmeasures.setEntId(tControlEntmeasuresExcel.getEntId());//企業id
controlEntmeasures.setDeviceId(tControlEntmeasuresExcel.getDeviceId());//設施id
...
...
...
int insertT_control_entmeasuress = tcontrolEntmeasuresService.insertT_control_entmeasuress(controlEntmeasures);//將資料插入 System.out.println(tControlEntmeasuresExcel.toString()); } }
ExcelUtiles.importExcel程式碼:
1 /** 2 * 功能描述:根據檔案路徑來匯入Excel 3 * @param filePath 檔案路徑 4 * @param titleRows 表標題的行數 5 * @param headerRows 表頭行數 6 * @param pojoClass Excel實體類 7 * @return 8 */ 9 public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) { 10 // 判斷檔案是否存在 11 if (StringUtils.isBlank(filePath)) { 12 return null; 13 } 14 ImportParams params = new ImportParams(); 15 params.setTitleRows(titleRows);//設定表標題行數 16 params.setHeadRows(headerRows);//設定表頭行數 17 List<T> list = null; 18 try { 19 list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); 20 } catch (NoSuchElementException e) { 21 // throw new RuntimeException("模板不能為空"); 22 e.printStackTrace(); 23 } catch (Exception e) { 24 e.printStackTrace(); 25 26 } 27 return list; 28 }
實體類程式碼:
1 public class TControlEntmeasuresExcel { 2 @Excel(name = "序號",orderNum = "0") 3 private String number; 4 @Excel(name = "年份",orderNum = "1") 5 private String year; 6 @Excel(name = "企業名稱",orderNum = "2") 7 private String entId; 8 @Excel(name = "設施名稱",orderNum = "3") 9 private String deviceId; 10 11 getter、setter和tostring方法
多sheet匯入
控制層程式碼:
1 @RequestMapping("/importAirPollutionElectricityData") 2 public void importAirPollutionElectricityData(MultipartFile file) { 3 4 String s = excelService.importSheets(file);
}
service層:
1 /** 2 * 多sheet匯入 3 * @param file 4 * @return 5 * @throws IOException 6 */ 7 @Override 8 public String importSheets(MultipartFile file){ 9 try { 10 // 根據file得到Workbook,主要是要根據這個物件獲取,傳過來的excel有幾個sheet頁 11 Workbook workBook = ExcelUtiles.getWorkBook(file); 12 StringBuilder sb=new StringBuilder(); 13 ImportParams params = new ImportParams(); 14 // 迴圈工作表Sheet 15 for (int numSheet = 0; numSheet < workBook.getNumberOfSheets(); numSheet++) { 16 // 第幾個sheet頁 17 params.setStartSheetIndex(numSheet); 18 // 驗證資料 19 params.setNeedVerfiy(true); 20 if(numSheet==0){ 21 // 表頭在第幾行 22 params.setTitleRows(1); 23 // 距離表頭中間有幾行不要的資料 24 params.setStartRows(0); 25 ExcelImportResult<ControlEntElectricity> result =ExcelImportUtil.importExcelMore(file.getInputStream(), 26 ControlEntElectricity.class, params); 27 // 校驗是否合格 28 if(result.isVerfiyFail()){ 29 // 不合格的資料 30 List<ControlEntElectricity> errorList = result.getList(); 31 // 拼湊錯誤資訊,自定義 32 for(int i=0;i<errorList.size();i++){ 33 ExcelUtiles.getWrongInfo(sb, errorList, i, errorList.get(i), "name", "。。資訊不合法"); 34 } 35 } 36 // 合格的資料 37 List<ControlEntElectricity> successList = result.getList(); 38 // 業務邏輯 39 System.out.println(successList.toString()); 40 }else if(numSheet==1){ 41 // 表頭在第幾行 42 params.setTitleRows(2); 43 // 距離表頭中間有幾行不要的資料 44 params.setStartRows(0); 45 ExcelImportResult<ControlEntElectricityDay> result =ExcelImportUtil.importExcelMore(file.getInputStream(), 46 ControlEntElectricityDay.class, params); 47 // 校驗是否合格 48 if(result.isVerfiyFail()){ 49 // 不合格的資料 50 List<ControlEntElectricityDay> errorList = result.getList(); 51 // 拼湊錯誤資訊,自定義 52 for(int i=0;i<errorList.size();i++){ 53 ExcelUtiles.getWrongInfo(sb, errorList, i, errorList.get(i), "name", "。。資訊不合法"); 54 } 55 } 56 // 校驗合格的資料 57 List<ControlEntElectricityDay> successList = result.getList(); 58 // 業務邏輯 59 System.out.println(successList.toString()); 60 } 61 62 } 63 } catch (Exception e) { 64 // log.error("匯入失敗:{}",e); 65 return "匯入失敗!請檢查匯入文件的格式是否正確"; 66 } 67 return "匯入成功!"; 68 }
ExcelUtiles.getWorkBook()和 ExcelUtiles.getWrongInfo()方法程式碼:
1 /** 2 * 得到Workbook物件 3 * @param file 4 * @return 5 * @throws IOException 6 */ 7 public static Workbook getWorkBook(MultipartFile file) throws IOException{ 8 //這樣寫 excel 能相容03和07 9 InputStream is = file.getInputStream(); 10 Workbook hssfWorkbook = null; 11 try { 12 hssfWorkbook = new HSSFWorkbook(is); 13 } catch (Exception ex) { 14 is =file.getInputStream(); 15 hssfWorkbook = new XSSFWorkbook(is); 16 } 17 return hssfWorkbook; 18 } 19 20 21 /** 22 * 得到錯誤資訊 23 * @param sb 24 * @param list 25 * @param i 26 * @param obj 27 * @param name 用哪個屬性名去表明不和規定的資料 28 * @param msg 29 * @throws Exception 30 */ 31 public static void getWrongInfo(StringBuilder sb,List list,int i,Object obj,String name,String msg) throws Exception{ 32 Class clazz=obj.getClass(); 33 Object str=null; 34 //得到屬性名陣列 35 Field[] fields = clazz.getDeclaredFields(); 36 for(Field f : fields){ 37 if(f.getName().equals(name)){ 38 //用來得到屬性的get和set方法 39 PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz); 40 //得到get方法 41 Method getMethod=pd.getReadMethod(); 42 str = getMethod.invoke(obj); 43 } 44 } 45 if(i==0) { 46 sb.append(msg + str + ";"); 47 } 48 else if(i==(list.size()-1)) { 49 sb.append(str + "</br>"); 50 } 51 else { 52 sb.append(str + ";"); 53 } 54 }
附上excel匯入匯出可能會用到的工具類程式碼ExcelUtiles.java:
1 package com.mapuni.datacenter.utils; 2 3 import cn.afterturn.easypoi.excel.ExcelExportUtil; 4 import cn.afterturn.easypoi.excel.ExcelImportUtil; 5 import cn.afterturn.easypoi.excel.entity.ExportParams; 6 import cn.afterturn.easypoi.excel.entity.ImportParams; 7 import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; 8 import org.apache.commons.lang3.StringUtils; 9 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 10 import org.apache.poi.ss.usermodel.Workbook; 11 import org.apache.poi.xssf.usermodel.XSSFWorkbook; 12 import org.springframework.web.multipart.MultipartFile; 13 14 import com.mapuni.datacenter.entity.ControlEntElectricity; 15 16 import javax.servlet.http.HttpServletResponse; 17 import java.io.File; 18 import java.io.IOException; 19 import java.io.InputStream; 20 import java.net.URLEncoder; 21 import java.util.List; 22 import java.util.Map; 23 import java.util.NoSuchElementException; 24 import java.beans.PropertyDescriptor; 25 import java.lang.reflect.Field; 26 import java.lang.reflect.Method; 27 28 /** 29 * @description: easypoiUtils 30 * 匯入匯出工具類 31 */ 32 public class ExcelUtiles { 33 34 /** 35 * 測試 36 * @param args 37 */ 38 public static void main(String[] args) { 39 List<ControlEntElectricity> list = ExcelUtiles.importExcel("D:\\5..27.xlsx", 0, 1, ControlEntElectricity.class); 40 System.out.println(list.toString()); 41 String s = "D:\\5..27.xlsx"; 42 System.out.println(s.substring(s.lastIndexOf("."))); 43 } 44 45 /** 46 * 功能描述:複雜匯出Excel,包括檔名以及表名。建立表頭 47 * @param list 匯出的實體類 48 * @param title 表頭名稱 49 * @param sheetName sheet表名 50 * @param pojoClass 對映的實體類 51 * @param isCreateHeader 是否建立表頭 52 * @param fileName 53 * @param response 54 * @return 55 */ 56 public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, 57 boolean isCreateHeader, HttpServletResponse response) { 58 ExportParams exportParams = new ExportParams(title, sheetName); 59 exportParams.setCreateHeadRows(isCreateHeader); 60 defaultExport(list, pojoClass, fileName, response, exportParams); 61 } 62 63 /** 64 * 功能描述:複雜匯出Excel,包括檔名以及表名,不建立表頭 65 * @param list 匯出的實體類 66 * @param title 表頭名稱 67 * @param sheetName sheet表名 68 * @param pojoClass 對映的實體類 69 * @param fileName 70 * @param response 71 * @return 72 */ 73 public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, 74 HttpServletResponse response) { 75 defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName)); 76 } 77 78 /** 79 * 功能描述:Map 集合匯出 80 * @param list 實體集合 81 * @param fileName 匯出的檔名稱 82 * @param response 83 * @return 84 */ 85 public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { 86 defaultExport(list, fileName, response); 87 } 88 89 /** 90 * 功能描述:預設匯出方法 91 * @param list 匯出的實體集合 92 * @param fileName 匯出的檔名 93 * @param pojoClass pojo實體 94 * @param exportParams ExportParams封裝實體 95 * @param response 96 * @return 97 */ 98 private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, 99 ExportParams exportParams) { 100 Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); 101 if (workbook != null) { 102 downLoadExcel(fileName, response, workbook); 103 } 104 } 105 106 /** 107 * 功能描述:Excel匯出 108 * @param fileName 檔名稱 109 * @param response 110 * @param workbook Excel物件 111 * @return 112 */ 113 private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) { 114 try { 115 response.setCharacterEncoding("UTF-8"); 116 response.setHeader("content-Type", "application/vnd.ms-excel"); 117 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); 118 workbook.write(response.getOutputStream()); 119 } catch (IOException e) { 120 // throw new NormalException(e.getMessage()); 121 } 122 } 123 124 /** 125 * 功能描述:預設匯出方法 126 * @param list 匯出的實體集合 127 * @param fileName 匯出的檔名 128 * @param response 129 * @return 130 */ 131 private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { 132 Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); 133 if (workbook != null) 134 ; 135 downLoadExcel(fileName, response, workbook); 136 } 137 138 /** 139 * 功能描述:根據檔案路徑來匯入Excel 140 * @param filePath 檔案路徑 141 * @param titleRows 表標題的行數 142 * @param headerRows 表頭行數 143 * @param pojoClass Excel實體類 144 * @return 145 */ 146 public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) { 147 // 判斷檔案是否存在 148 if (StringUtils.isBlank(filePath)) { 149 return null; 150 } 151 ImportParams params = new ImportParams(); 152 params.setTitleRows(titleRows); 153 params.setHeadRows(headerRows); 154 List<T> list = null; 155 try { 156 list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); 157 } catch (NoSuchElementException e) { 158 // throw new RuntimeException("模板不能為空"); 159 e.printStackTrace(); 160 } catch (Exception e) { 161 e.printStackTrace(); 162 163 } 164 return list; 165 } 166 167 /** 168 * 功能描述:根據接收的Excel檔案來匯入Excel,並封裝成實體類 169 * @param file 上傳的檔案 170 * @param titleRows 表標題的行數 171 * @param headerRows 表頭行數 172 * @param pojoClass Excel實體類 173 * @return 174 */ 175 public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, 176 Class<T> pojoClass) { 177 if (file == null) { 178 return null; 179 } 180 ImportParams params = new ImportParams(); 181 params.setTitleRows(titleRows); 182 params.setHeadRows(headerRows); 183 List<T> list = null; 184 try { 185 list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); 186 } catch (NoSuchElementException e) { 187 // throw new NormalException("excel檔案不能為空"); 188 } catch (Exception e) { 189 // throw new NormalException(e.getMessage()); 190 System.out.println(e.getMessage()); 191 } 192 return list; 193 } 194 /** 195 * 得到Workbook物件 196 * @param file 197 * @return 198 * @throws IOException 199 */ 200 public static Workbook getWorkBook(MultipartFile file) throws IOException{ 201 //這樣寫 excel 能相容03和07 202 InputStream is = file.getInputStream(); 203 Workbook hssfWorkbook = null; 204 try { 205 hssfWorkbook = new HSSFWorkbook(is); 206 } catch (Exception ex) { 207 is =file.getInputStream(); 208 hssfWorkbook = new XSSFWorkbook(is); 209 } 210 return hssfWorkbook; 211 } 212 213 /** 214 * 得到錯誤資訊 215 * @param sb 216 * @param list 217 * @param i 218 * @param obj 219 * @param name 用哪個屬性名去表明不和規定的資料 220 * @param msg 221 * @throws Exception 222 */ 223 public static void getWrongInfo(StringBuilder sb,List list,int i,Object obj,String name,String msg) throws Exception{ 224 Class clazz=obj.getClass(); 225 Object str=null; 226 //得到屬性名陣列 227 Field[] fields = clazz.getDeclaredFields(); 228 for(Field f : fields){ 229 if(f.getName().equals(name)){ 230 //用來得到屬性的get和set方法 231 PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz); 232 //得到get方法 233 Method getMethod=pd.getReadMethod(); 234 str = getMethod.invoke(obj); 235 } 236 } 237 if(i==0) { 238 sb.append(msg + str + ";"); 239 } 240 else if(i==(list.size()-1)) { 241 sb.append(str + "</br>"); 242 } 243 else { 244 sb.append(str + ";"); 245 } 246 } 247 248 249 }