<dependency> <groupId>jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency>
1.获取固定头
public WritableWorkbook requireExportHead(String fileurl, String fileName,
HttpServletResponse response) throws UnsupportedEncodingException,
IOException, BiffException {
String filename = fileName+".xls";
String filenameUTF8 = URLEncoder.encode(filename,"UTF-8"); //防止URL乱码
OutputStream os =response .getOutputStream();//取得客户端输出流
response.reset();// 清空输出流
response.setHeader("Content-disposition","attachment; filename=""+filenameUTF8+""");// 设定输出文件头
response.setContentType("application/x-msdownload"); // 定义输出类型
String path = this.getClass().getClassLoader().getResource(fileurl).getPath();
File file = new File(path);
Workbook workbook = Workbook.getWorkbook(file);
WritableWorkbook book = Workbook.createWorkbook(os,workbook);
return book;
}
2.下载excel
excle模板test.xls
controler中:
String fileurl = "excle/test.xls";
String fileName = "fileName";
public void downloadExcel(String fileurl,String fileName,HttpServletResponse response)
throws BiffException, IOException, WriteException{
WritableWorkbook book = getExportHead(fileurl, fileName, response);
book.write();
book.close();
}
3.导入excle
<input type="file" id="upload" name="upload">
private HttpServletRequest request; //private HttpServletResponse response; String fileName = request.getAttribute("upload"); Workbook book = null; try { book = Workbook.getWorkbook(new File(fileName)); // 获得第一个工作表对象 Sheet sheet = book.getSheet(0); int rows=sheet.getRows(); int columns=sheet.getColumns(); //遍历每行每列的单元格 for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++){ Cell cell = sheet.getCell(j, i); String content = cell.getContents(); } } } catch (Exception e) { e.printStackTrace(); return "导入失败"; }finally{ if(book!=null){ book.close(); } }