artDialog 配置参数: http://www.cnblogs.com/mfc-itblog/p/5648717.html
jQuery插件之ajaxFileUpload: http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html
页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title></title> <!--引入弹窗组件start--> <!-- <script type="text/javascript" src="${base}/res/zDialog/zDrag.js"></script> <script type="text/javascript" src="${base}/res/zDialog/zDialog.js"></script> --> --> <link href="${base}/res/artDialog-5.0.4/skins/default.css" rel="stylesheet" type="text/css"/> <script src="${base}/res/artDialog-5.0.4/artDialog.min.js" type="text/javascript"></script> <script type="text/javascript" src="${base}/res/ajaxfileupload/ajaxfileupload.js"></script> <script type="text/javascript"> //alert("${base}"); var iDialog ; function importDialog(){ var updateHtml = '<p id="importMessage" style="display:none;">正在导入信息...</p>'+ '<table id="updateTable">'+ '<tr>'+ '<td style="width:40px;text-align: right;">文件:</td>'+ '<td><input type="file" id="execelFile" name="execelFile" onchange="fileType(this)"/></td>'+ '</tr>'+ '<tr>'+ '<td style="text-align: center;" colspan="2">'+ '<input class="upload-file" type="button" value="上传" onclick="update()" style="height:20px;width:120px;margin-left:50px;"/>'+ '</td>'+ '</tr>'+ '</table>'; $("#content").html(updateHtml); var htmlContent = $("#content").html(); iDialog = $("#importDialog").dialog({ title:"信息导入",height: 150,width: 350,modal: true,content:htmlContent }); $("#content").css("display","table"); } function fileType(obj){ var fileType=obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase();//获得文件后缀名 if(fileType != '.xls' ){ alert("仅可上传Excel2003文件格式(.xls)"); $("#execelFile").val(''); } var fileName = obj.value; $("#fileName").val(fileName); } function update(){ if($("#execelFile").val()==""){ alert("仅可上传Excel2003文件格式(.xls)"); $("#execelFile").val(''); } $("#updateTable").css("display","none"); $("#importMessage").css("display","inline-block"); $.ajaxFileUpload({ url : "importExcel.do",secureuri : false,fileElementId : 'execelFile',dataType : 'text',success : function(data) { $("#content").html(data); //alert(data); //iDialog.close(); },error : function(data) { location.reload(); } }); } </script> </head> <body> <div> <input class="query" type="button" value="导入" onclick="importDialog();" style="height:20px;width:120px;margin-left: 115px;"/> [align=right;]文件:</td> <td><input type="text" id="fileName" name="fileName" /></td> <td><input type="file" id="execelFile" name="execelFile" onchange="fileType(this)"/></td> </tr> <tr> <td style="text-align: center;" colspan="2"> <input class="upload-file" type="button" value="上传" onclick="update()" style="height:20px;width:120px;margin-left:50px;"/> </td> </tr> </table> --> [/align] </div> </body> </html>
//Controller
@RequestMapping(value = "/test/importExcel") public void importExcel(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "execelFile",required = false) MultipartFile file) { ... testService.importExcel(file) ... }
//TestService
public String importExcel(MultipartFile file) throws ExcelParseException { String result = null; // 存入服务器目录 String fileName = ""; String filePath = PathUtil.getClasspath(); if (file != null && file.getSize() > 0) { fileName = FileUpload.fileUp(file,filePath,DateUtil.getSeconds()); } try{ // 读取Excel文件 List<HashMap> readExcel = ExcelUtils.readExcel(filePath,fileName,0); if (readExcel == null || readExcel.size() <= 1) { throw new ExcelParseException("读取文件失败!可能原因如下:\n1、文件为无效文件\n2、文件无记录"); } //数据库操作 } ... }
//Excel读取工具
package util; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import jxl.Workbook; import jxl.format.Alignment; import jxl.format.Border; import jxl.format.BorderLineStyle; import jxl.format.VerticalAlignment; import jxl.write.Colour; import jxl.write.Label; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class ExcelUtils { /** * @param filepath //文件路径 * @param filename //文件名 * @param startrow //开始行号 * @param startcol //开始列号 * @param sheetnum //sheet * @return list */ @SuppressWarnings({ "rawtypes","unchecked" }) public static List<HashMap> readExcel(String filepath,String filename,int startrow,int startcol,int sheetnum) { List<HashMap> varList = new ArrayList<HashMap>(); try { File target = new File(filepath,filename); FileInputStream fi = new FileInputStream(target); HSSFWorkbook wb = new HSSFWorkbook(fi); HSSFSheet sheet = wb.getSheetAt(sheetnum); //sheet 从0开始 int rowNum = sheet.getLastRowNum() + 1; //取得最后一行的行号 for (int i = startrow; i < rowNum; i++) { //行循环开始 HashMap varpd = new HashMap(); HSSFRow row = sheet.getRow(i); //行 int cellNum = row.getLastCellNum(); //每行的最后一个单元格位置 for (int j = startcol; j < cellNum; j++) { //列循环开始 HSSFCell cell = row.getCell(Short.parseShort(j + "")); String cellValue = null; if (null != cell) { switch (cell.getCellType()) { // 判断excel单元格内容的格式,并对其进行转换,以便插入数据库 case 0: cellValue = String.valueOf((int) cell.getNumericCellValue()); break; case 1: cellValue = cell.getStringCellValue(); break; case 2: cellValue = cell.getNumericCellValue() + ""; // cellValue = String.valueOf(cell.getDateCellValue()); break; case 3: cellValue = ""; break; case 4: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case 5: cellValue = String.valueOf(cell.getErrorCellValue()); break; } } else { cellValue = ""; } varpd.put("var"+j,cellValue); } varList.add(varpd); } } catch (Exception e) { System.out.println(e); } return varList; } /** * @param dirPath:文件要保存的目录 * @param fileName:文件要保存的文件名 * @param title:报表的题目 * @param columnTitle:列名集合(类型为List) * @param text:正文数据(类型为两级嵌套List) * return boolean */ public static boolean writeExcel(String dirPath,String fileName,String title,List columnTitle,List text) { WritableWorkbook workBook = null; WritableSheet sheet = null; if (dirPath == null || "".equals(dirPath) || fileName == null || "".equals(fileName)) { System.out.println("建立excel文件失败:路径或文件名为空"); return false; } File filePath = new File(dirPath); if (!filePath.exists()) { // 如果文件要保存的目录不存在则产生该目录 if (!filePath.mkdir()) { System.out.println("建立excel文件失败:无法建立该目录"); return false; } } // 在该目录下产生要保存的文件名 String excelPath = dirPath + "/" + fileName + ".xls"; File excelFile = new File(excelPath); // 以下开始输出到EXCEL try { if (!excelFile.exists()) { if (!excelFile.createNewFile()) { System.out.println("建立excel文件失败:建立excel文件发生异常"); return false; } } /** **********创建工作簿************ */ workBook = Workbook.createWorkbook(excelFile); /** **********创建工作表************ */ sheet = workBook.createSheet("Sheet1",0); // SheetSettings sheetSet = sheet.getSettings(); // sheetSet.setProtected(false); /** ************设置单元格字体************** */ WritableFont headFont = new WritableFont(WritableFont.createFont("宋体"),16,WritableFont.BOLD); WritableFont head2Font = new WritableFont(WritableFont.createFont("宋体"),13,WritableFont.BOLD); /** ************以下设置几种格式的单元格************ */ // 用于表头 WritableCellFormat wcf_head = new WritableCellFormat(headFont); wcf_head.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐 wcf_head.setAlignment(Alignment.CENTRE); // 文字水平对齐 wcf_head.setWrap(false); // 文字是否换行 // 用于第三行列名 WritableCellFormat wcf_column = new WritableCellFormat(head2Font); wcf_column.setBorder(Border.ALL,BorderLineStyle.THIN); // 线条 wcf_column.setVerticalAlignment(VerticalAlignment.TOP); wcf_column.setAlignment(Alignment.LEFT); // 文字左对齐 wcf_column.setBackground(Colour.GRAY_25); wcf_column.setWrap(true); // 文字是否换行 // 用于正文 WritableCellFormat wcf_center = new WritableCellFormat(new WritableFont(WritableFont.createFont("宋体"),13)); wcf_center.setBorder(Border.ALL,BorderLineStyle.THIN); // 线条 wcf_center.setVerticalAlignment(VerticalAlignment.TOP); // 文字垂直对齐 wcf_center.setAlignment(Alignment.LEFT); // 文字水平对齐 wcf_center.setWrap(true); // 文字是否换行 /** ************单元格格式设置完成****************** */ sheet.setColumnView(0,10);sheet.setColumnView(1,10);sheet.setColumnView(2,20); sheet.setColumnView(3,16);sheet.setColumnView(4,16);sheet.setColumnView(5,20); sheet.setColumnView(6,20);sheet.setColumnView(7,19);sheet.setColumnView(8,16); sheet.setColumnView(9,16);sheet.setColumnView(10,16);sheet.setColumnView(11,16); sheet.setRowView(0,640); sheet.getSettings().setLeftMargin(0.1d);//0.1d=0.26cm sheet.getSettings().setRightMargin(0.1d); /** ***************以下是报表的内容********************* */ // 合并单元格设置excel的题目 sheet.mergeCells(0,columnTitle.size() - 1,0); sheet.addCell(new Label(0,title,wcf_head)); int x = 1; // 设置列名 for (int i = 0; i < columnTitle.size(); i++) { sheet.addCell(new Label(i,x,String.valueOf(columnTitle.get(i)),wcf_column)); } x = x + 1; // 写入正文数据 for (int i = 0; i < text.size(); i++) { List content = (List) text.get(i); if (content != null && content.size() > 0) { for (int j = 0; j < content.size(); j++) { String data = String.valueOf(content.get(j)); sheet.addCell(new Label(j,x + i,data,wcf_center)); } } } /** **********以上所写的内容都是写在缓存中的,下一句将缓存的内容写到文件中******** */ workBook.write(); } catch (Exception e) { System.out.println("建立excel文件失败:" + e.getMessage()); return false; } finally { /** *********关闭文件************* */ try { if (workBook != null) { workBook.close(); } } catch (Exception ex) { System.out.println("关闭文件流失败:" + ex.getMessage()); return false; } } return true; } }原文链接:https://www.f2er.com/ajax/161384.html