前言:网上对java excel处理比较杂乱,我经过查阅资料并亲自试验,总结了一下java excel的导出和读取
.xls格式的excel文件需要HSSF支持,需要相应的poi.jar,.xlsx格式的excel文件需要XSSF支持,需要poi-ooxml.jar,
引入poi-3.7-20101029.jar包和poi-ooxml-3.7-20101029.jar(我用的maven没有试验这种jar包引入)
我的是maven项目,则在pom中加入
org.apache.poi
poi
3.6
org.apache.poi
poi-ooxml
3.6
package com.equipment.util;
import com.alibaba.fastjson.JSON;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ExcelUtil {
private final static String excel2003L = ".xls"; // 2003- 版本的excel
private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//声明列对象
HSSFCell cell = null;
//创建标题
for(int i=0;i(读取Excel)
*
* @param in
* 输入流
* @param fileName
* 文件名(判断Excel版本)
* @param mapping
* 字段名称映射
* @return
* @throws Exception
*/
public static List
注:其中HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER)
可以设置表格的样式,具体样式详情可以看这个:
https://blog.csdn.net/qq_35192741/article/details/77645018
/**
* 导出报表
* @return
*/
@RequestMapping(value = "/exportRepairOrder")
@ResponseBody
public void exportRepairOrder(@RequestParam Map params, HttpServletRequest req,HttpServletResponse response) throws Exception {
//获取数据
List> list = repairManagerService.getRepairOrderList(params);
//excel标题
String[] title = {"地市","区县","营业厅ID","营业厅名称","渠道电话","设备类型","设备名称","报修日期"};
//excel文件名
String fileName = "维护单表"+System.currentTimeMillis()+".xls";
//sheet名
String sheetName = "维护单表";
String [][] content = new String[list.size()][];
for (int i = 0; i < list.size(); i++) {
content[i] = new String[title.length];
Map obj = list.get(i);
content[i][0] = obj.get("REGION_GROUP_NAME")==null?"":obj.get("REGION_GROUP_NAME").toString();
content[i][1] = obj.get("DISTRICT_GROUP_NAME")==null?"":obj.get("DISTRICT_GROUP_NAME").toString();
content[i][2] = obj.get("GROUP_ID")==null?"":obj.get("GROUP_ID").toString();
content[i][3] = obj.get("GROUP_NAME")==null?"":obj.get("GROUP_NAME").toString();
content[i][4] = obj.get("CHANNEL_CONTACT")==null?"":obj.get("CHANNEL_CONTACT").toString();
content[i][5] = obj.get("DEVICE_CATEGORY_NAME")==null?"":obj.get("DEVICE_CATEGORY_NAME").toString();
content[i][6] = obj.get("DEVICE_NAME")==null?"":obj.get("DEVICE_NAME").toString();
content[i][7] = obj.get("REPORT_DATE1")==null?"":obj.get("REPORT_DATE1").toString();
}
//创建HSSFWorkbook
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
//响应到客户端
try {
this.setResponseHeader(response, fileName);
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//发送响应流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
点击导出按钮,则将页面url设为接口,并将页面的查询参数也传进去,可以做到导出页面经过查询条件过滤后的数据
报修日期:
-
报修工号:
维修单状态:
/*导出Excel*/
function exportExcel(){
var url = "${ctx }/repairOrder/exportRepairOrder?"
var parameter = "loginNo="+ $("#loginNo").val()
+"&orderStatus="+$('#orderStatus').val()
+"&datemin="+$('#datemin').val()
+ "&datemax=" + $("#datemax").val();
window.location.href = url+parameter;
}
点击后即下载excel文件,打开文件后表格跟html中的表格基本一致
因为使用的spring mvc,所以文件取multipart格式比较容易,然后在手动转成inputstream
关于读取excel我是参考这边博客
https://blog.csdn.net/u012662357/article/details/58593020
此接口可以自动识别xls和xlsx
html:
文件上传
js:
//上传文件
function uploadExcel(){
$("#file").trigger("click");
$("#file").change(function(){
var formData = new FormData($("#form1")[0]); //重点:要用这种方法接收表单的参数
$.ajax({
url : "${ctx }/statistics/uploadExcel",
type : 'POST',
data : formData,
// 告诉jQuery不要去处理发送的数据
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
async : false,
success : function(data) {
if(data){
console.log(data)
}
}
});
})
}
@ResponseBody
@RequestMapping(value = "uploadExcel", produces = "text/plain;charset=UTF-8")
public String uploadExcel(@RequestParam Map params,
@RequestParam(value = "file") MultipartFile file) {
RetBase ret=new RetBase();
List> list=new ArrayList>();
try {
String fileName = file.getOriginalFilename();
//将multipartFile转为inputstream
CommonsMultipartFile cFile = (CommonsMultipartFile) file;
DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem();
InputStream inputStream = fileItem.getInputStream();
Map titleMap=new HashMap<>();
titleMap.put("id", "id");
titleMap.put("姓名", "name");
titleMap.put("年龄", "age");
list=ExcelUtil.readExcel(inputStream,fileName,titleMap);
ret.setData(list);
ret.setSuccess(true);
ret.setMsg("成功");
} catch (Exception e) {
e.printStackTrace();
ret.setMsg("失败");
ret.setSuccess(false);
}
return JSON.toJSONString(ret, SerializerFeature.WriteMapNullValue);
}
上传的excel
返回的数据: