POI import and export Excel dropdown multi-level interaction

 Reference: https://blog.csdn.net/m0_37956938/article/details/78084503

 Front-end code:

<table class="add_table" cellpadding="0" cellspacing="0">
<tr class="main_table_tr">
<td class="td_title" style="width: 25%;"><p class="add_table_p2"> 第一步:</p></td>
<td>
<p style="float: left; margin-left: 10px; font-size: 14px;"> 下载 </p>
<a href="<%=path %>/api/busi/daily/data/downloadTemplate?emId= '${emId}'" style="float: left; margin-left: 11px; font-size: 14px; width: auto;" onclick="downloadExcel(this);"> 日常库内容模板 </a>
</td>
</tr>
<tr class="main_table_tr">
<td class="td_title" style="width: 25%;"><p class="add_table_p2"> 第二步:</p></td>
<td>
<input type="file" id="file" name="file" style="display: none"/>
<input type="text" id="filename" style="border: none; width: auto; display:none" />
<input type="button" onclick="getExcel()" value="选择文件" />
</td>
</tr>
</table>
 
// Select excel and upload 
function getExcel () {
$ ( "File #") the Click ();.
$ ( '# File') Change (function (E) {.
Var fileName = e.target.files [0]; // js Get Object file
IF (fileName == undefined!) {
var file_typename = fileName.name.substring (fileName.name.lastIndexOf () '.');
IF (file_typename === '.xlsx' file_typename = || == '* .xls') {
$ ( "filename #") Val (fileName.name);.
uploadExcel (fileName);
} the else {
layer.alert ( "Please select the correct file type!");
}
} the else {
layer.alert ( "Please select the correct file!");
}
});
}

// upload 
function uploadExcel (fileName) {
var form the FormData new new = (); // the FormData objects
form.append ( "file", fileName) ; // file object
form.append ( "dailyId", '$ {id}' );
form.append ( "EMID", '$ {} EMID');
$ .ajax ({
URL: '<% =% path> / API / BuSi / Daily / Data / uploadExcel', // URL address
type: 'POST', // uploading
data: form, // encapsulated data upload formdata
dataType: 'the JSON',
cache: to false, // do not cache
processData: false, // jQuery not to process data transmitted
contentType: false, // jQuery not to set the Content-Type request header
success:function (data) {// success callback
if (data.success) {
layer.alert ( "import is successful", function () {
window.parent.location.reload ();
});
} the else {
$ ( "# errorTip") Find ( "span") HTML (data.message).. ;
}
},
error: function (Data) {// failure callback
layer.alert ( "! import fails, please try again later");
}
});
}
// download Excel template 
function downloadExcel (obj) {
var = the baseUrl "specific download path";
$ (obj) .attr ( "the href", the baseUrl);
$ (obj) [0] .click ();
}

backend Code:

/ ** 
* Download Excel Template
* @param Request
* @param the Response
* @throws IOException
* /
@ RequestMapping ( "/ downloadTemplate")
public void downloadTemplate (String EMID, Request the HttpServletRequest, HttpServletResponse the Response) throws IOException {
Workbook Workbook = new new XSSFWorkbook ();
String fileName = "template_daily_library" + ".xlsx"; // Excel file name
OutputStream os = null;
Workbook = the buildExcelDocument (EMID);
response.reset (); // clear the output stream
MIME type // web browsing by excel file type is determined
response.setHeader ( "the Content-type",
"file application / vnd.ms-excel; charset = UTF-. 8");

// file name processing. Prevent file name garbled
// Content-disposition attribute is arranged as an attachment for download
Response.AddHeader ( "the Content-Disposition", "Attachment; filename ="
+ new new String (fileName.getBytes ( "GB2312"), "ISO8859-1"));
os = response.getOutputStream (); // obtaining the output stream
workbook.write (OS);
}

/ **
* Create Excel
* @param EMID
* @return
* /
public XSSFWorkbook the buildExcelDocument (String EMID) {
// create a Excel
XSSFWorkbook = new new XSSFWorkbook Workbook ();
// a pattern
XSSFFont font1 workbook.createFont = ();
font1.setFontHeightInPoints ((Short) 12 is); // set the font size
font1.setFontName ( "Song"); // set the font style, such as: Arial, Microsoft elegant black
font1.setItalic (false);// italic true italics

// style two
XSSFFont font2 = workbook.createFont ();
font2.setFontHeightInPoints ((Short) 12); // set the font size
font2.setFontName ( "Song"); // set the font style, such as: Arial, Microsoft elegant black and other
font2.setColor (Font.COLOR_RED); // red mandatory
font2.setItalic (false); // true italics italics

XSSFCellStyle style1 = workbook.createCellStyle (); // Gets the style 1
XSSFCellStyle style2 = Workbook. createCellStyle (); // get style 2


// Search the two components a member name
list <String> part1List = new ArrayList <String> (); // a member list
list <String> strList6 = new ArrayList < String> (); // cycle unit list
strList6.add ( "Year");
strList6.add ( "May");
strList6.add ( "week");
strList6.add ( "day");

List <String> strList7 = new ArrayList <String> (); // job abnormal return type list
strList7.add ( "early warning");

// sort data into a Map, mapkey father storage location, value the storage location sub-region in
the Map <String, List <String >> new new = the HashMap Map <String, List <>> String ();

// a member
Map <String, Object> params1 = new HashMap <String, Object> () ;
query query1 = new new query (params1);
query1.put ( "deleteFlag", DelStatus.status_Y); // default query does not delete
query1.put ( "the parentId", "IS null");
query1.put ( "EMID" , EMID);
List <DevicePartBean> parts1 = devicePartBiz.selectByQuery (Query1); // a member

// two members
Map <String, Object> params2 = new HashMap <String,Object>();
Query query2 = new Query(params2);
query2.put ( "deleteFlag", DelStatus.status_Y) ; // default query does not delete the

List <DevicePartBean> parts2 = null;
for (DevicePartBean p1: parts1) {
String partId1 = p1.getId ();
String partName1 = p1.getPartName ();
part1List.add (partName1);
query2.put ( "EMID", EMID);
query2.put ( "the parentId", partId1);
parts2 = devicePartBiz.selectByQuery (of query2); // two members
List <String> part2List = new ArrayList <String> ( ); // two parts list
for (DevicePartBean Part2: parts2) {
String partName2 part2.getPartName = ();
part2List.add (partName2);
}
map.put (partName1, part2List);
}

// create a special page is used to store two hidden sheet member a member
Sheet hideSheet = workbook.createSheet ( "site_sheet");
workbook.setSheetHidden (workbook.getSheetIndex ( "site_sheet"), to true);

int = 0 the rowId ;
// set the first line, a member information storage
row part1Row = hideSheet.createRow (the rowId ++);
part1Row.createCell (0) .setCellValue ( "a member list");
for (int I = 0; I < part1List.size (); I ++) {
the Cell part1Cell part1Row.createCell = (I +. 1);
part1Cell.setCellValue (part1List.get (I));
}
// writes specific data into each row, for the beginning of the line parent region, sub-region followed by
the Iterator <String> keyIterator = map.keySet () Iterator ();.
the while (keyIterator.hasNext ()) {
String Key = keyIterator.next ();
List<String> son = map.get(key);

Row row = hideSheet.createRow(rowId++);
row.createCell(0).setCellValue(key);
for (int i = 0; i < son.size(); i++) {
Cell cell = row.createCell(i + 1);
cell.setCellValue(son.get(i));
}

// 添加名称管理器
String range = getRange(1, rowId, son.size());
Name name = workbook.createName();
name.setNameName(key);
String formula = "site_sheet!" + range;
name.setRefersToFormula(formula);
}

XSSFSheet sheet1 = workbook.createSheet("sheet1");
Row row0 = sheet1.createRow(0);

String [] headers = new String [ ] { " a member", "secondary member", "Job Content *", "* the SOP job", "* tool methods", "* operating cycle", "period * unit "," * exception return type job "," exception handling program * "};
for (int I = 0; I <headers.length; I ++) {
sheet1.setColumnWidth (I, 5000); // set each column column width of
the Cell Cell row0.createCell = (I, Cell.CELL_TYPE_STRING);
IF (I == I == 0 ||. 1) {
style1.setFont (font1); // used to select the desired font format
cell.setCellStyle ( style1);
} the else {
style2.setFont (font2); // needs to select the font format used
cell.setCellStyle (style2);
}

cell.setCellValue (headers [I]);
}

XSSFDataValidationHelper dvHelper = new new XSSFDataValidationHelper (Sheet1);
// a regular member
PartConstraint = dvHelper.createExplicitListConstraint DataValidationConstraint (part1List.toArray (new new String [] {}));
// four parameters are: start line, end line, start column, end columns
CellRangeAddressList partRangeAddressList = new CellRangeAddressList (1, 200 , 0, 0);
DataValidation partDataValidation = dvHelper.createValidation (partConstraint, partRangeAddressList);
// verify
partDataValidation.createErrorBox ( "error", "select the correct one member");
partDataValidation.setShowErrorBox (to true);
partDataValidation.setSuppressDropDownArrow (to true);
sheet1.addValidationData (partDataValidation);

// cycle unit rule
DataValidationConstraint cycleUnitConstraint = dvHelper.createExplicitListConstraint (strList6.toArray (new String [] {}));
// four parameters are: start line, end line, start column, end columns
CellRangeAddressList cycleUnitRangeAddressList new new CellRangeAddressList = (. 1, 200 is,. 6,. 6);
DataValidation cycleUnitDataValidation = dvHelper.createValidation (cycleUnitConstraint, cycleUnitRangeAddressList);
// verify
cycleUnitDataValidation.createErrorBox ( "error", "Please select the correct cycle unit");
cycleUnitDataValidation.setShowErrorBox (to true);
cycleUnitDataValidation.setSuppressDropDownArrow (to true);
sheet1.addValidationData (cycleUnitDataValidation);

// return type operation exception rules
DataValidationConstraint exceptConstraint = dvHelper.createExplicitListConstraint (strList7.toArray (new new String [] {}));
// four parameters are: start line, end line, start column, end columns
= New new CellRangeAddressList exceptRangeAddressList CellRangeAddressList (. 1, 200 is,. 7,. 7);
DataValidation exceptDataValidation = dvHelper.createValidation (exceptConstraint, exceptRangeAddressList);
// verify
exceptDataValidation.createErrorBox ( "error", "Please select the correct operation exception return type");
exceptDataValidation.setShowErrorBox (to true);
exceptDataValidation.setSuppressDropDownArrow (to true);
sheet1.addValidationData (exceptDataValidation);


// set the validity of the first 20 rows
for (int I = 2; I <200 is; I ++) {
setDataValidation ( "A", Sheet1, I, 2);
}

return Workbook;
}

/ **
* set the validity
* @param offset main influence the column of the cell, i.e. this cell unit by a linkage which affect cell
* @param sheet
* @param rowNum 行数
* @param colNum 列数
*/
public static void setDataValidation(String offset,XSSFSheet sheet, int rowNum,int colNum) {
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
DataValidation data_validation_list;
data_validation_list = getDataValidationByFormula(
"INDIRECT($" + offset + (rowNum) + ")", rowNum, colNum,dvHelper);
sheet.addValidationData(data_validation_list);
}

/**
* 加载下拉列表内容
* @param formulaString
* @param naturalRowIndex
* @param naturalColumnIndex
* @param dvHelper
* @return
*/
private static DataValidation getDataValidationByFormula(
FormulaString String, naturalRowIndex int, int naturalColumnIndex, XSSFDataValidationHelper dvHelper) {
// load the drop-down list contents
@ Example: If formulaString = "INDIRECT ($ A $ 2)" will be represented by the rule data acquisition key value from the cell A2 with name manager the same data,
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createFormulaListConstraint (formulaString);
// set the data validity in which cell loading.
// four parameters are: start line, end line, start column, end columns
int firstRow naturalRowIndex = -1;
int = naturalRowIndex lastRow -. 1;
int = naturalColumnIndex the FirstCol -. 1;
int lastCol naturalColumnIndex = -. 1;
CellRangeAddressList = new new CellRangeAddressList Regions (firstRow,
lastRow, the FirstCol, lastCol);
// data Validation objects
// binds
XSSFDataValidation data_validation_list = (XSSFDataValidation) dvHelper.createValidation (dvConstraint, Regions);
data_validation_list.setEmptyCellAllowed (to false);
IF (data_validation_list the instanceof XSSFDataValidation) {
data_validation_list.setSuppressDropDownArrow (to true);
data_validation_list.setShowErrorBox (to true);
} the else {
data_validation_list.setSuppressDropDownArrow (to false);
}
// set the input information message
data_validation_list.createPromptBox ( "drop-down selection prompt", "Please use the drop mode to select the appropriate value!");
// set the input error message
//data_validation_list.createErrorBox ( "select error", "value you entered is not in the candidate list, select the appropriate value pull-down!");
return data_validation_list;
}

/**
*
* @Param offset the offset, if a 0, A represents the starting column 1, that is, from column B
* @param rowId few lines
* @param colCount total of how many columns
* @return if the parameters to 1,1, 10 represents the B1-K1. The final return B $ 1 $: $ K $ 1
*
* @author wb 2020 January 4 15:00:00
* /
public static String GetRange (int offset, int rowId, int colCount) {
char Start = (char) ( ' A '+ offset);
IF (colCount <= 25) {
char End = (char) (Start + colCount -. 1);
return "$" + Start + "$" + the rowId + ": $" + End + "$ "+ the rowId;
} the else {
char endPrefix = 'A';
char endSuffix = 'A';


endSuffix = (char)('A' + 25);
} else {
endSuffix = (char)('A' + (colCount - 25) % 26 - 1);
}
} else {// 51以上
if ((colCount - 25) % 26 == 0) {
endSuffix = (char)('A' + 25);
endPrefix = (char)(endPrefix + (colCount - 25) / 26 - 1);
} else {
endSuffix = (char)('A' + (colCount - 25) % 26 - 1);
endPrefix = (char)(endPrefix + (colCount - 25) / 26);
}
}
return "$" + start + "$" + rowId + ":$" + endPrefix + endSuffix + "$" + rowId;
}
}


/**
* 上传Excel
*/
@RequestMapping(value = "/uploadExcel", method = RequestMethod.POST)
@ResponseBody
public String uploadExcel (@RequestParam("dailyId") String dailyId, @RequestParam("emId") String emId, @RequestParam(value="file", required = false) MultipartFile file) {
boolean flag = false;
try {
List<DailyLibraryDataBean> list = ExcelUtils.readExcel("", DailyLibraryDataBean.class, file);
String msg = "";
for (int i=1;i<=list.size();i++) {
DailyLibraryDataBean data = list.get(i-1);
data.setDailyId(dailyId);
String ms = "";
DevicePartBean bean = new DevicePartBean();
if (!"".equals(data.getPartId()) && data.getPartId() != null) {

bean = devicePartBiz.fetch(Cnd.where("part_name", "=", data.getPartId()).and("parent_id", "is", null).and("em_id", "=", emId));

if (bean != null) {
data.setPartId(bean.getId());

if (!"".equals(data.getPartId2()) && data.getPartId2() != null) {
DevicePartBean bean2 = devicePartBiz.fetch(Cnd.where("part_name", "=", data.getPartId2()).and("parent_id", "=", bean.getId()).and("em_id", "=", emId));
if (bean2 != null) {
data.setPartId2(bean2.getId());
} else {
ms + = "first" + i + "row two check there is no member device model;";
}
} the else {
data.setPartId2 ( "");
}
} the else {
ms + = "first" + i + "row Device a model check there is no member; ";
}
} the else {
data.setPartId (" ");
}

IF (" ".equals (data.getDailyContent ()) || data.getDailyContent () == null) {
MS + = "on" + i + "row job can not be empty;";
}
IF ( "" .equals (data.getDailySop ()) || Data.getDailySop () == null) {
MS + = "first" + i + "row SOP job can not be empty;";
}
IF ( "" .equals (data.getDailyTool ()) || data.getDailyTool () == null) {
MS + = "first" + i + "line tool method can not be empty;";
}
IF ( "" .equals (data.getCycle ()) || data.getCycle () == null) {
MS + = "first" + i + "row cycle time can not be empty;";
}
IF ( "" .equals (Data. getCycleUnit ()) || data.getCycleUnit () == null) {
MS + = "first" + i + "row cycle unit can not be empty;";
} the else {
Switch (data.getCycleUnit ()) {
Case "in ": data.setCycleUnit (" cycle_unit_year ");
BREAK;

Case" month ": data.setCycleUnit("cycle_unit_month");
break;

case "Week": data.setCycleUnit ( "cycle_unit_week");
BREAK;

case "Day": data.setCycleUnit ( "cycle_unit_day");
BREAK;

default: MS + = "first" + i + "row check there is no cycle unit ; ";
BREAK;
}
}
IF (" ".equals (data.getExcepResultType ()) || data.getExcepResultType () == null) {
MS + =" first "+ i +" exception return line job type can not be null ; ";
} the else {
Switch (data.getExcepResultType ()) {
Case" warning ": data.setExcepResultType (" excep_result_alarm ") ;
break;

default: ms + = "first" + i + "row check there is no job exception return type;";
BREAK;
}
}
IF ( "" .equals (data.getExcepSchemes ()) || data.getExcepSchemes () == null ) {
MS + = "first" + i + "row exception handling scheme can not be empty;";
}
IF (StringUtils.isNotBlank (MS)) {
MS + = "\ R & lt \ n-";
MSG = + MS;
Continue;
}
dataBiz.insert (Data);
}
IF (StringUtils.isNotBlank (MSG)) {
return Json.toJson (new new ApiResult (MSG));
}
In Flag = to true;
} catch (Exception e) {
e.printStackTrace();
}

return Json.toJson(new ApiResult(flag, flag == true));
}


public class ExcelUtils {

private final static Logger log = LoggerFactory.getLogger(ExcelUtils.class);

private final static String EXCEL2003 = "xls";
private final static String EXCEL2007 = "xlsx";

public static <T> List<T> readExcel(String path, Class<T> cls,MultipartFile file){

String fileName = file.getOriginalFilename();
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
log.error("上传文件格式不正确");
}
List<T> dataList = new ArrayList<>();
Workbook workbook = null;
try {
InputStream is = file.getInputStream();
if (fileName.endsWith(EXCEL2007)) {
// FileInputStream is = new FileInputStream(new File(path));
workbook = new XSSFWorkbook(is);
}
if (fileName.endsWith(EXCEL2003)) {
// FileInputStream is = new FileInputStream(new File(path));
workbook = new HSSFWorkbook(is);
}
if (workbook != null) {
//类映射 注解 value-->bean columns
Map<String, List<Field>> classMap = new HashMap<>();
List<Field> fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());
fields.forEach(
field -> {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null) {
String value = annotation.value();
if (StringUtils.isBlank(value)) {
return;//return起到的作用和continue是相同的 语法
}
if (!classMap.containsKey(value)) {
classMap.put(value, new ArrayList<>());
}
field.setAccessible(true);
classMap.get(value).add(field);
}
}
);
//索引-->columns
Map<Integer, List<Field>> reflectionMap = new HashMap<>(16);
//默认读取第一个sheet
Sheet sheet = workbook.getSheetAt(0);

boolean firstRow = true;
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
//首行 提取注解
if (firstRow) {
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
CellValue getCellValue = String (Cell);
IF (classMap.containsKey (CellValue)) {
reflectionMap.put (J, classMap.get (CellValue));
}
}
firstRow = to false;
} the else {
// Blank lines are ignored
if (row = null =) {
Continue;
}
the try {
T T = cls.newInstance ();
if it is determined that a blank line //
boolean allBlank = true;
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
if (reflectionMap.containsKey(j)) {
Cell cell = row.getCell(j);
String cellValue = getCellValue(cell);
if (StringUtils.isNotBlank(cellValue)) {
allBlank = false;
}
List<Field> fieldList = reflectionMap.get(j);
fieldList.forEach(
x -> {
try {
handleField(t, cellValue, x);
} catch (Exception e) {
log.error(String.format("reflect field:%s value:%s exception!", x.getName(), cellValue), e);
}
}
);
}
}
if (!allBlank) {
dataList.add(t);
} else {
log.warn(String.format("row:%s is blank ignore!", i));
}
} catch (Exception e) {
log.error(String.format("parse row:%s exception!", i), e);
}
}
}
}
} catch (Exception e) {
log.error(String.format("parse excel exception!"), e);
} finally {
if (workbook != null) {
try {
// workbook.close();
} catch (Exception e) {
log.error(String.format("parse excel exception!"), e);
}
}
}
return dataList;
}

private static <T> void handleField(T t, String value, Field field) throws Exception {
Class<?> type = field.getType();
if (type == null || type == void.class || StringUtils.isBlank(value)) {
return;
}
if (type == Object.class) {
field.set(t, value);
//数字类型
} else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {
if (type == int.class || type == Integer.class) {
field.set(t, NumberUtils.toInt(value));
} else if (type == long.class || type == Long.class) {
field.set(t, NumberUtils.toLong(value));
} else if (type == byte.class || type == Byte.class) {
field.set(t, NumberUtils.toByte(value));
} else if (type == short.class || type == Short.class) {
field.set(t, NumberUtils.toShort(value));
} else if (type == double.class || type == Double.class) {
field.set(t, NumberUtils.toDouble(value));
} else if (type == float.class || type == Float.class) {
field.set(t, NumberUtils.toFloat(value));
} else if (type == char.class || type == Character.class) {
field.set(t, CharUtils.toChar(value));
} else if (type == boolean.class) {
field.set(t, BooleanUtils.toBoolean(value));
} else if (type == BigDecimal.class) {
field.set(t, new BigDecimal(value));
}
} else if (type == Boolean.class) {
field.set(t, BooleanUtils.toBoolean(value));
} else if (type == Date.class) {
//
field.set(t, value);
} else if (type == String.class) {
field.set(t, value);
} else {
Constructor<?> constructor = type.getConstructor(String.class);
field.set(t, constructor.newInstance(value));
}
}

private static String getCellValue(Cell cell) {
if (cell == null) {
return "";
}
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
} else {
return new BigDecimal(cell.getNumericCellValue()).toString();
}
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return StringUtils.trimToEmpty(cell.getStringCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return StringUtils.trimToEmpty(cell.getCellFormula());
} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
return "ERROR";
} else {
return cell.toString().trim();
}

}
}
 

Guess you like

Origin www.cnblogs.com/wzb0228/p/12196257.html