導出工具類:
public class ExportExcel {
private String headerName;
private WritableCellFormat headerFormat;
private WritableCellFormat titleFormat;
public ExportExcel(String headerName) {
super();
this.headerName = headerName;
WritableFont headerfont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false);
headerFormat = new WritableCellFormat(headerfont);
try {
headerFormat.setAlignment(jxl.format.Alignment.CENTRE);
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 11, WritableFont.BOLD, false);
titleFormat = new WritableCellFormat(titlefont);
try {
titleFormat.setAlignment(jxl.format.Alignment.CENTRE);
titleFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.MEDIUM);
titleFormat.setBackground(jxl.format.Colour.GRAY_25);
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getSlotExcelByBomNo(List<Slot> slots) {
WritableWorkbook book = null;
String fileName = "exports/" +slots.get(0).getBomNo()+"_"+ System.currentTimeMillis() + ".xls";
try {
book = Workbook.createWorkbook(new File(SystemContextLoaderListener.getServletContext()
.getRealPath(fileName)));
WritableSheet sheet = book.createSheet("Sheet_1", 0);
// 字體
WritableFont normalfont = new WritableFont(WritableFont.ARIAL, 10);
WritableCellFormat normalFormat = new WritableCellFormat(normalfont);
normalFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
NumberFormat fivedps = new NumberFormat("#.##");
WritableCellFormat floatFormat = new WritableCellFormat(fivedps);
floatFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN);
// Calendar ca = Calendar.getInstance();
// ca.set(year, month, 1);
// int maxDay = ca.getActualMaximum(Calendar.DAY_OF_MONTH);
// 標題頭
sheet.mergeCells(0, 0, 8, 0);
String titleName = headerName ;
sheet.addCell(new Label(0, 0, titleName, headerFormat));
sheet.addCell(new Label(0, 1, "站位", titleFormat));
sheet.addCell(new Label(1, 1, "作業類型", titleFormat));
sheet.addCell(new Label(2, 1, "測試環節序列號", titleFormat));
sheet.addCell(new Label(3, 1, "物料編號", titleFormat));
sheet.addCell(new Label(4, 1, "物料名", titleFormat));
sheet.addCell(new Label(5, 1, "物料型號", titleFormat));
sheet.addCell(new Label(6, 1, "使用量", titleFormat));
sheet.addCell(new Label(7, 1, "BOM版次", titleFormat));
sheet.addCell(new Label(8,1,"備註",titleFormat));
sheet.setColumnView(0, 15);
sheet.setColumnView(1, 20);
sheet.setColumnView(2, 25);
sheet.setColumnView(3, 20);
sheet.setColumnView(4, 20);
sheet.setColumnView(5, 20);
sheet.setColumnView(6,20);
sheet.setColumnView(7,20);
sheet.setColumnView(8,20);
sheet.setRowView(0, 500); // 設置行的高度
sheet.setRowView(1, 400); // 設置行的高度
for (int i = 0; i < slots.size(); i++) {
sheet.setRowView(i + 2, 350); // 設置行的高度
// SNRecord snRecord = snRecords.get(i);
Slot slot = slots.get(i);
sheet.addCell(new Label(0, i + 2, slot.getSlotCode(), normalFormat));
sheet.addCell(new Label(1, i + 2, slot.getOperationTypeName(), normalFormat));
sheet.addCell(new Number(2, i + 2, slot.getSeqNum(), normalFormat));
sheet.addCell(new Label(3,i+2,slot.getItemNo(),normalFormat));
sheet.addCell(new Label(4, i + 2, slot.getItemName(), normalFormat));
sheet.addCell(new Label(5, i + 2, slot.getModel(), normalFormat));
sheet.addCell(new Number(6, i + 2, slot.getUsingQty(), normalFormat));
sheet.addCell(new Label(7, i + 2,slot.getBomNo(), normalFormat));
sheet.addCell(new Label(8, i + 2,slot.getRemark(), normalFormat));
}
book.write();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (book != null)
try {
{
book.close();
}
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return fileName;
}
業務層:
@Override
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public String exportByBomNo(String bomNo) {
List<Slot> slots = slotDao.findByBomNo(bomNo);
ExportExcel exportExcel = new ExportExcel(bomNo);
return exportExcel.getSlotExcelByBomNo(slots);
}
控制層:
@RequestMapping(value = "exportByBomNo", method = RequestMethod.GET)
public String exportByBomNo(@RequestParam("BomNo") String BomNo) {
String path = slotService.exportByBomNo(BomNo);
return "redirect:../" + path;
}
jsp:
<input type="button" class="btn" value="導出數據" οnclick="exportByBomNo()">
js:
function exportByBomNo() {
var bomNo = $("#BomNoCode").val()
if(bomNo==""||bomNo==undefined) {
jAlert('請確認查詢條件','溫馨提示');
} else {
window.location.target='_blank'
window.location.href = "exportByBomNo.do?BomNo="+bomNo;
}
}
導入功能:
工具類:
public class ImportExcelData {
public static List<Slot> readExcel(String fileName, String path) throws Exception {
final String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
if ("xlsx".equalsIgnoreCase(extension)) {
return read2007Excel(path);
} else if ("xls".equalsIgnoreCase(extension)) {
return read2003Excel(path);
}
return null;
}
public static List<Slot> read2003Excel(String path) throws Exception {
List<Slot> slots = new ArrayList<>();
//同時支持Excel 2007
File excelFile = new File(path); //創建文件對象
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelFile));
// 讀取第一章表格內容
HSSFRow row;
int sheetCount = workbook.getNumberOfSheets(); //Sheet的數量
//遍歷每個Sheet
for (int s = 0; s < sheetCount; s++) {
HSSFSheet sheet = workbook.getSheetAt(s);
int rowCount = sheet.getPhysicalNumberOfRows(); //獲取總行數
//遍歷每一行
for (int r = 2; r < rowCount; r++) {
row = sheet.getRow(r);
// Meter meter = new Meter();
Slot slot = new Slot();
//遍歷每一列
HSSFCell cell1 = row.getCell(0);
if(cell1 == null){
break;
}
//基礎信息Code
slot.setSlotCode(cell1.getStringCellValue());
cell1 = row.getCell(1);
//作業類型
String operationTypeName = cell1.getStringCellValue().trim();
if(operationTypeName.equals("料件組裝")){
slot.setOperationType(OperationType.ASSEMBLE);
}else if(operationTypeName.equals("功能測試")){
slot.setOperationType(OperationType.FUNCTIONTEST);
}
cell1 = row.getCell(2);
//測試環節序列號
slot.setSeqNum((int)cell1.getNumericCellValue());
cell1 = row.getCell(3);
//物料名稱
slot.setItemNo(cell1.getStringCellValue());
cell1=row.getCell(4);
//物料編碼
slot.setItemName(cell1.getStringCellValue());
cell1=row.getCell(5);
//物料型號
slot.setModel(cell1.getStringCellValue());
cell1=row.getCell(6);
//物料使用量
slot.setUsingQty((int)cell1.getNumericCellValue());
cell1=row.getCell(7);
//BOM版次
slot.setBomNo(cell1.getStringCellValue());
cell1=row.getCell(8);
//備註
slot.setRemark(cell1.getStringCellValue());
slots.add(slot);
}
}
return slots;
}
public static List<Slot> read2007Excel(String path) throws Exception {
List<Slot> slots = new ArrayList<>();
//同時支持Excel 2007
File excelFile = new File(path); //創建文件對象
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(excelFile));
// 讀取第一章表格內容
XSSFRow row;
int sheetCount = workbook.getNumberOfSheets(); //Sheet的數量
//遍歷每個Sheet
for (int s = 0; s < sheetCount; s++) {
XSSFSheet sheet = workbook.getSheetAt(s);
int rowCount = sheet.getPhysicalNumberOfRows(); //獲取總行數
//遍歷每一行
for (int r = 1; r < rowCount; r++) {
row = sheet.getRow(r);
Slot slot = new Slot();
//遍歷每一列
XSSFCell cell1 = row.getCell(0);
if(cell1 == null){
break;
}
//站位Code
slot.setSlotCode(cell1.getStringCellValue());
cell1 = row.getCell(1);
//作業類型
String operationTypeName = cell1.getStringCellValue().trim();
if(operationTypeName.equals("料件組裝")){
slot.setOperationType(OperationType.ASSEMBLE);
}else if(operationTypeName.equals("功能測試")){
slot.setOperationType(OperationType.FUNCTIONTEST);
}
cell1 = row.getCell(2);
//測試環節序列號
slot.setSeqNum((int)cell1.getNumericCellValue());
cell1 = row.getCell(3);
//物料名稱
slot.setItemNo(cell1.getStringCellValue());
cell1=row.getCell(4);
//物料編碼
slot.setItemName(cell1.getStringCellValue());
cell1=row.getCell(5);
//物料型號
slot.setModel(cell1.getStringCellValue());
cell1=row.getCell(6);
//物料使用量
slot.setUsingQty((int)cell1.getNumericCellValue());
cell1=row.getCell(7);
//BOM版次
slot.setBomNo(cell1.getStringCellValue());
cell1=row.getCell(8);
//備註
slot.setRemark(cell1.getStringCellValue());
slots.add(slot);
}
}
return slots;
}
private static String fillZero(String uid) {
int len = uid.length();
for (int i = len; i < 12; i++) {
uid = "0" + uid;
}
if(len > 12){
uid = uid.substring(len-12,len);
}
return uid;
}
}
控制層:
@RequestMapping(value = "importSlots",method = RequestMethod.POST)
@ResponseBody
public String importSlots(MultipartFile myfile,HttpServletRequest request) {
try {
if (myfile.isEmpty()) {
return "false";
} else {
String fileName = myfile.getOriginalFilename();
final String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
if (!"xlsx".equalsIgnoreCase(extension) && !"xls".equalsIgnoreCase(extension)) {
return 1 / 0 + "";
}
String realPath = request.getSession().getServletContext().getRealPath("/upload");
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
//這裏不必處理IO流關閉的問題,因爲FileUtils.copyInputStreamToFile()方法內部會自動把用到的IO流關掉,我是看它的源碼才知道的
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
String path = realPath + File.separator + fileName;
List<Slot> existSlots = slotService.readExcel(fileName, path);
return new Gson().toJson(existSlots);
}
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}
業務層:
@Override
public List<Slot> readExcel(String fileName, String path) throws Exception {
List<Slot> exisSlots = new ArrayList<>();
List<Slot> slots = ImportExcelData.readExcel(fileName,path);
for(Slot slot : slots) {
Slot existSlot;
if(LogicUtils.isNullOrEmpty(slot.getItemNo())){
existSlot = slotDao.findByBomNoAndSlotCode(slot.getBomNo(),slot.getSlotCode());
}else{
existSlot = slotDao.findByBomNoAndItemNoAndSlotCode(slot.getBomNo(),slot.getItemNo(),slot.getSlotCode());
}
if(LogicUtils.isNull(existSlot)) { //若沒有插入時,則直接插入
slotDao.save(slot);
} else { //否則覆蓋之前數據
existSlot.setRemark(slot.getRemark());
existSlot.setModel(slot.getModel());
existSlot.setUsingQty(slot.getUsingQty());
existSlot.setItemName(slot.getItemName());
existSlot.setSlotCode(slot.getSlotCode());
exisSlots.add(existSlot);
}
}
return exisSlots;
}
jsp頁面:有一個kendo寫的彈出框:
<input type="button" class="btn" value="導入數據" οnclick="improtBox()">
<kendo:window name="addSlot" title="上傳工位信息" draggable="true" resizable="true" width="500" height="400" visible="false">
<kendo:window-content>
<div >
<form id="submitSlots" action="importSlots.do" method="post" enctype="multipart/form-data" style="font: 14px bold ;" >
<fieldset>
<legend>點擊瀏覽選擇上傳文件</legend>
<input type="file" name="myfile" id="myfile" style="color:red;"/>
<%-- <input type="submit" value="上傳工位信息" class="btn btn-primary" style="position: relative;right:70px;"/>;--%>
</fieldset>
<fieldset>
日誌:<textarea rows="10" id="log" style="position: relative;right:0px;margin-top: 10px;width:380px" ></textarea>
</fieldset>
<div class="heading-buttons">
<div class="buttons pull-right" style="margin-right: 0px; margin-top: 20px;">
<input type="button" id="submitButton" class="btn btn-primary right" value="確定" οnclick="improtSlots();"/>
</div>
</div>
</form>
</div>
</kendo:window-content>
</kendo:window>
js 如下:
//當點擊導入時,觸發
function improtBox(){
var depository = $("#addSlot");
//清空上傳文件返回的日誌信息
$("#log").val("");
//清空上傳文件的信息
var file = $("#myfile")
file.after(file.clone().val(""));
file.remove();
//顯示確定按鈕
$("#submitButton").css("display","block");
depository.data("kendoWindow").center();
depository.data("kendoWindow").open();
}
function improtSlots() {
var filepath=$("#myfile").val();
var extStart=filepath.lastIndexOf(".");
var ext=filepath.substring(extStart,filepath.length).toUpperCase();
if(ext!=".XLS"&&ext!=".XLSX"){
jAlert("文件僅限於後綴爲xls,xlsx的Excel格式","溫馨提示"); //檢測允許的上傳文件類型
return false;
}
if(confirm("確定導入工位信息?")){
$("#log").val("正在導入...");
$("#submitSlots").ajaxSubmit({
type: 'post',
url: "importSlots.do" ,
success: function(data){
if(data == "false"){
$("#log").val("導入失敗!");
}else{
var msg = "導入成功!";
var obj = JSON.parse(data);
var arrayLen = obj.length;
if (arrayLen > 0) {
msg += "\n以下重複:";
for (var i = 0; i < arrayLen; i++) {
if(obj[i].itemNo==undefined||obj[i].itemNo==""){
msg += "\n" + "BOM號:"+obj[i].bomNo+"站位:"+obj[i].slotCode+" 物料號:無";
}else{
msg += "\n" + "BOM號:"+obj[i].bomNo+"站位:"+obj[i].slotCode+" 物料號:"+obj[i].itemNo;
}
}
}
$("#log").val(msg);
$("#submitButton").css("display","none");
}
},
error: function(XmlHttpRequest, textStatus, errorThrown){
$("#log").val("導入異常!");
$("#submitButton").css("display","none");
}
});
}
}