依赖maven坐标
org.apache.poi
poi-ooxml
3.9
代码片
.
package com.it.utils;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ImportExcelUtil {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List>对象
* @param in,fileName
* @return
* @throws IOException
*/
public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
List<List<Object>> list = null;
//创建Excel工作薄
Workbook work = this.getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//遍历所有的列
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(this.getCellValue(cell));
}
list.add(li);
}
}
in.close();
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param inStr,fileName
* @return
* @throws Exception
*/
public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
* @param cell
* @return
*/
public Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}else{
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
return value;
}
}
代码片
.
package com.it.ui.controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.it.entity.Books;
import com.it.service.BooksService;
import com.it.utils.ImportExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
@RequestMapping("/uploadExcel")
public class LeadingExcelController {
@Autowired
private BooksService service=null;
@RequestMapping("/form")
public String form(HttpServletRequest request)throws Exception{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
InputStream in =null;
List<List<Object>> listob = null;
MultipartFile file = multipartRequest.getFile("upfile");
if(file.isEmpty()){
throw new Exception("文件不存在!");
}
in = file.getInputStream();
listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
in.close();
System.out.println(listob.size());
//该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
Books Books = new Books();
Books.setBookname(String.valueOf(lo.get(1)));
Books.setBookAuthor(String.valueOf(lo.get(2)));
Books.setBookPublish(String.valueOf(lo.get(3)));
Books.setBookPrice(String.valueOf(lo.get(4)));
Books.setCreate_date(String.valueOf(lo.get(5)));
service.add(Books);
System.out.println("打印信息-->"+Books.getCreate_date());
}
return "redirect:/list";
}
@RequestMapping(value="/ajax")
public void ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
InputStream in =null;
List<List<Object>> listob = null;
MultipartFile file = multipartRequest.getFile("upfile");
if(file.isEmpty()){
throw new Exception("文件不存在!");
}
in = file.getInputStream();
listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
//该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
Books Books = new Books();
Books.setBookname(String.valueOf(lo.get(1)));
Books.setBookAuthor(String.valueOf(lo.get(2)));
Books.setBookPublish(String.valueOf(lo.get(3)));
Books.setBookPrice(String.valueOf(lo.get(4)));
Books.setCreate_date(String.valueOf(lo.get(5)));
System.out.println("打印信息-->"+Books.getCreate_date());
service.add(Books);
}
PrintWriter out = null;
response.setCharacterEncoding("utf-8"); //防止ajax接受到的中文信息乱码
out = response.getWriter();
out.print("文件导入成功!");
out.flush();
out.close();
}
@RequestMapping(value = "/downLoadExcel", method = RequestMethod.GET)
public String downLoadExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
List<Books> meteoMonitors = service.findAll();
if (meteoMonitors != null && meteoMonitors.size() > 0) {
String fileName = "test.xlsx";
response.setHeader("Content-disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"), "ISO8859-1"));//设置文件头编码格式
response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");//设置类型
response.setHeader("Cache-Control", "no-cache");//设置头
response.setDateHeader("Expires", 0);//设置日期头
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
/* CellStyle headStyle = workbook.createCellStyle();
headStyle.setFillPattern(CellStyle.THIN_HORZ_BANDS);
headStyle.setFillBackgroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());*/
XSSFCellStyle style = workbook.createCellStyle();
//设置背景颜色
style.setFillForegroundColor(HSSFColor.LIME.index);
//solid 填充 foreground 前景色
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
Row row = sheet.createRow(0);
Cell c1 = row.createCell(0);
//cell.setCellStyle(cellStyle);
c1.setCellValue("id");
c1.setCellStyle(style);
Cell c2 = row.createCell(1);
c2.setCellValue("书名");
c2.setCellStyle(style);
Cell c3 = row.createCell(2);
c3.setCellValue("作者");
c3.setCellStyle(style);
Cell c4 = row.createCell(3);
c4.setCellValue("出版社");
c4.setCellStyle(style);
Cell c5 = row.createCell(4);
c5.setCellValue("价格");
c5.setCellStyle(style);
Cell c6 = row.createCell(5);
c6.setCellValue("日期");
c6.setCellStyle(style);
// row.setRowStyle(headStyle);
int rowNum = 1;
for (Books meteoMonitor:meteoMonitors) {
Row t = sheet.createRow(rowNum);
Cell cell = t.createCell(0);
//cell.setCellStyle(cellStyle);
cell.setCellValue(meteoMonitor.getBookid());
Cell cell1 = t.createCell(1);
cell1.setCellValue(meteoMonitor.getBookname());
Cell cell2 = t.createCell(2);
cell2.setCellValue(meteoMonitor.getBookAuthor());
Cell cell3 = t.createCell(3);
cell3.setCellValue(meteoMonitor.getBookPublish());
Cell cell4 = t.createCell(4);
cell4.setCellValue(meteoMonitor.getBookPrice());
Cell cell5 = t.createCell(5);
cell5.setCellValue(meteoMonitor.getCreate_date());
rowNum++;
}
workbook.write(response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}
return null;
}
}
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>列表</title>
<style>
#main{width:80%;margin:10px auto}
tr{border: 0px}
</style>
</head>
<body>
<div id="main">
<table style="border:1px solid black;text-align:center"width="100%">
<tr>
<td colspan="8" style="text-align:center">
<form id="ff" action="/page" method="post">
<input type="hidden" name="page" id="page" value="1"/>
<select name="nameType">
<option value="">全部</option>
<option value="bookPublish">出版社</option>
<option value="booksname">书名</option>
<option value="bookAuthor">作者</option>
</select>
<input type="text" class="text" value="${text}" name="text"/>
<input class="sub" type="submit" value="搜索"/>
</form>
</td>
</tr>
<tr style="background-color: darkgrey">
<td>编号</td>
<td>书名</td>
<td>作者</td>
<td>价格</td>
<td>出版社</td>
<td>发布日期</td>
<td>操作</td>
</tr>
<c:forEach var="o" items="${list }">
<tr class="textTable">
<td>${o.bookid }</td>
<td>${o.bookname }</td>
<td>${o.bookAuthor }</td>
<td>${o.bookPrice }</td>
<td>${o.bookPublish }</td>
<td>${o.create_date }</td>
<td><a href="">编辑</a>
</tr>
</c:forEach>
</table>
<div style="text-align:center;width: 100%">
<a href="javascript:getPage(1)">首页</a>
<a href="javascript:getPage(${currentpage-1 })">上一页</a>
<a href="javascript:getPage(${currentpage+1 })">下一页</a>
<a href="javascript:getPage(${pagecount})">末页</a>
第${currentpage}页/共${pagecount }页
</div>
<form method="POST" enctype="multipart/form-data" id="form1" action="uploadExcel/form">
<label>上传文件: </label>
<input id="upfile" type="file" name="upfile"><br> <br>
<input type="submit" value="表单提交" onclick="return checkData()">
<input type="button" value="ajax提交" id="btn" name="btn" >
</form>
<a href="uploadExcel/downLoadExcel">导出报表</a>
</div>
<script type="text/javascript" src="../../js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="../../js/jquery.form.js"></script>
<script>
/* ajax 方式上传文件操作 */
$(document).ready(function(){
$("#btn").click(function(){ if(checkData()){
alert("fdf");
$('#form1').ajaxSubmit({
url:'uploadExcel/ajax',
dataType: 'text',
success: resutlMsg,
error: errorMsg
});
function resutlMsg(msg){
alert(msg);
$("#upfile").val("");
}
function errorMsg(){
alert("导入excel出错!");
}
}
});
});
//JS校验form表单信息
function checkData(){
var fileDir = $("#upfile").val();
var suffix = fileDir.substr(fileDir.lastIndexOf("."));
if("" == fileDir){
alert("选择需要导入的Excel文件!");
return false;
}
if(".xls" != suffix && ".xlsx" != suffix ){
alert("选择Excel格式的文件导入!");
return false;
}
return true;
}
$("tr:odd").css("background-color","darkgrey");
$(".sub").click(function () {
if($(".text").val()==""||$(".text").val()==null){
alert("text不能为空");
return false;
}
})
function getPage(index)
{
$("#page").val(index);
$("#ff").submit();
}
</script>
</body>
</html>
希望和大家一起学习!如有需要改正,评论留言!