导入excel:java代码如下:
private static final long serialVersionUID = -2201219701121037194L; private String savePath="upload"; private ServletContext sc; private ExcelWorkSheet<Ptoject> excelWorkSheet; public void init(ServletConfig config) { // savePath = config.getInitParameter("savePath"); sc = config.getServletContext(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request);// 上传文件解析 Iterator itr = items.iterator();// 枚举方法 while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) {// 判断是文件还是文本信息 System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8")); } else { if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件 System.out.println("上传文件的大小:" + item.getSize()); System.out.println("上传文件的类型:" + item.getContentType()); // item.getName()返回上传文件在客户端的完整路径名称 System.out.println("上传文件的名称:" + item.getName()); // 此时文件暂存在服务器的内存当中 File tempFile = new File(item.getName());// 构造临时对象 File file = new File(sc.getRealPath("/") + "upload", tempFile.getName()); // 获取根目录对应的真实物理路径 item.write(file);// 保存文件在服务器的物理磁盘中
//以上代码文servelt上传文件,下面为读取excel Workbook workbook = createWorkbook(new FileInputStream(file),item.getName()); Sheet sheet = workbook.getSheetAt(0); excelWorkSheet = new ExcelWorkSheet<Ptoject>(); excelWorkSheet.setSheetName(sheet.getSheetName()); Row firstRow = sheet.getRow(1); Iterator<Cell> iterator = firstRow.iterator(); List<String> cellNames = new ArrayList<String>(); while (iterator.hasNext()) { cellNames.add(iterator.next().getStringCellValue()); } excelWorkSheet.setColumns(cellNames); for(int i=2;i<=sheet.getLastRowNum();i++){ Row row = sheet.getRow(i); Ptoject ptoject = new Ptoject(); ptoject.setLastproject(row.getCell(0).getStringCellValue()); ptoject.setNextproject(row.getCell(1).getStringCellValue()); ptoject.setMaindept(row.getCell(2).getStringCellValue()); ptoject.setAcotrdept(row.getCell(3).getStringCellValue()); ptoject.setBeizhu(row.getCell(4).getStringCellValue()); excelWorkSheet.getData().add(ptoject); } request.setAttribute("context",excelWorkSheet); } else { request.setAttribute("upload.message", "没有选择上传文件!"); } } } } catch (Exception e) { e.printStackTrace(); request.setAttribute("upload.message", "上传文件失败!"); } request.getRequestDispatcher("/uploadResult.jsp").forward(request, response); } private Workbook createWorkbook(InputStream is,String filename) throws IOException{ if (filename.toLowerCase().endsWith("xls")) { return new HSSFWorkbook(is); }else if (filename.toLowerCase().endsWith("xlsx")) { return new XSSFWorkbook(is); } return null; }
ptoject.java代码如下
package org.test.entity; public class Ptoject { String lastproject; String nextproject; String maindept; String acotrdept; String beizhu; public String getLastproject() { return lastproject; } public void setLastproject(String lastproject) { this.lastproject = lastproject; } public String getNextproject() { return nextproject; } public void setNextproject(String nextproject) { this.nextproject = nextproject; } public String getMaindept() { return maindept; } public void setMaindept(String maindept) { this.maindept = maindept; } public String getAcotrdept() { return acotrdept; } public void setAcotrdept(String acotrdept) { this.acotrdept = acotrdept; } public String getBeizhu() { return beizhu; } public void setBeizhu(String beizhu) { this.beizhu = beizhu; } }
ExcelWorkSheet.java代码如下
package org.test.entity; import java.util.ArrayList; import java.util.List; public class ExcelWorkSheet<T> { private String sheetName; private List<T> data = new ArrayList<T>(); private List<String> columns; public String getSheetName() { return sheetName; } public void setSheetName(String sheetName) { this.sheetName = sheetName; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public List<String> getColumns() { return columns; } public void setColumns(List<String> columns) { this.columns = columns; } }
html代码如下:
<form action="ReadExcelServlet" method="post" enctype="multipart/form-data" > <input type="file" name="filename" ><br> <input type="submit" value="提交"> </form> //用来上传文件
<table border="1"> <tr> <c:forEach items="${context.columns}" var="column"> <td>${column}</td> </c:forEach> </tr> <c:forEach items="${context.data}" var="excel"> <tr> <td>${excel.lastproject}</td> <td>${excel.nextproject}</td> <td>${excel.maindept}</td> <td>${excel.acotrdept}</td> <td>${excel.beizhu}</td> </tr> </c:forEach> </table>
//jsp读取excel中的值
生成excel:java代码如下:
private String format="xlsx"; private HttpServletResponse response; private String fileName; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/octet-stream;charset=utf-8"); try { response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(this.fileName,"utf-8")); } catch (Exception e) { // TODO: handle exception } //setFormat(request.getParameter("format")); format = request.getParameter("format"); if ("xls".equals(format)) { this.fileName = "导出数据.xls"; } if("xlsx".equals(format)){ this.fileName = "导出数据.xlsx"; } exportExcel(response.getOutputStream(), format); response.getOutputStream().flush(); response.getOutputStream().close(); // request.getRequestDispatcher("index.jsp").forward(request, response); } private void exportExcel(OutputStream os,String format){ Workbook workbook = null; if("xls".equals(format)){ workbook = new HSSFWorkbook(); } if("xlsx".equals(format)){ workbook = new XSSFWorkbook(); } Sheet sheet = workbook.createSheet("学生信息"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("学号"); row.createCell(1).setCellValue("姓名"); row.createCell(2).setCellValue("性别"); row.createCell(3).setCellValue("生日"); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); List<Student> list = new ArrayList<Student>(); Student student = new Student(); student.setId(1); student.setName("李明"); student.setSex("男"); student.setBrithday(new Date()); list.add(student); for(int i=0;i<list.size();i++){ Row row2 = sheet.createRow(i+1); Student st= list.get(i); row2.createCell(0).setCellValue(st.getId()); row2.createCell(1).setCellValue(st.getName()); row2.createCell(2).setCellValue(st.getSex()); Cell cell = row2.createCell(3); cell.setCellValue(st.getBrithday()); cell.setCellStyle(cellStyle); } try { workbook.write(os); } catch (Exception e) { // TODO: handle exception } }
student.java代码:
package org.test.entity; import java.util.Date; public class Student { private int id; private String name; private String sex; private Date brithday; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBrithday() { return brithday; } public void setBrithday(Date brithday) { this.brithday = brithday; } }
html代码:
<a href="WriteExcelServlet?format=xls">将数据导出到Excel文件(.xls格式)</a><br> <a href="WriteExcelServlet?format=xlsx">将数据导出到Excel文件(.xlsx格式)</a>
所要导入的包: