您的位置:首页 > 其它

Excel文件导出导入

2018-01-02 20:25 302 查看

导出原理分析

文件的导出功能和文件的下载功能类似,都是从服务器读取数据,然后将数据发送到客户端(浏览器端);客户端可自动下载;

1.请求的方式必须是同步的,有两种方式可以选择

<a href="http://localhost:8080/down">文件导出</a>

<input type="butten" name="export" value="文件导出" onclick="download()"/>

function download(){
window.location.href="/down"
}


2.服务端的代码
添加maven依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>

@GetMapping("/down")
public String importComment(HttpServletResponse response) {
CommentQueryData data = new CommentQueryData();
data.setCurrentPage(1);
data.setDisplayCount(0);
PageCount findComment = dataApi.findComment(data);
// 在mongdb中查询所有数据

List<Map<String, Object>> rows = (List<Map<String, Object>>) findComment.getRows();
// 将数据写到excel文件里面

HSSFWorkbook excel = createExcel(rows);
// 将文件写到reposne里面 带到浏览器端

String name = System.currentTimeMillis() + ".xls";
try {
// 直接获取输出,直接输出excel

OutputStream output = response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(name, "utf-8"));
response.setContentType("application/msexcel")<
4000
span class="hljs-comment">;
// 将excel直接写到response中返回

excel.write(output);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return "SUCCESS";
}

/**

*

* @ClassDescribe:将数据库封装到workbook中

* @author:shaowei

* @createDate:2018年1月2日 上午9:06:58

* @updateAuthor:

* @updateDate:

* @param list

* @return

*/
private HSSFWorkbook createExcel(List<Map<String, Object>> list) {
// 创建一个Excel文件

HSSFWorkbook workbook = new HSSFWorkbook();
// 创建一个工作表

HSSFSheet sheet = workbook.createSheet("评论统计表");
// 添加表头行

HSSFRow hssfRow = sheet.createRow(0);
// 设置单元格格式居中

HSSFCellStyle cellStyle = workbook.createCellStyle();

cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

// 添加表头内容

sheet.setColumnWidth(0, 20 * 256);
HSSFCell headCell = hssfRow.createCell(0);
headCell.setCellValue("昵称");
headCell.setCellStyle(cellStyle);

sheet.setColumnWidth(1, 60 * 256);
headCell = hssfRow.createCell(1);
headCell.setCellValue("评论内容");
headCell.setCellStyle(cellStyle);

sheet.setColumnWidth(2, 10 * 256);
headCell = hssfRow.createCell(2);
headCell.setCellValue("是否推荐");
headCell.setCellStyle(cellStyle);

sheet.setColumnWidth(3, 10 * 256);
headCell = hssfRow.createCell(3);
headCell.setCellValue("点赞数");
headCell.setCellStyle(cellStyle);

sheet.setColumnWidth(4, 30 * 256);
headCell = hssfRow.createCell(4);
headCell.setCellValue("创建时间");
headCell.setCellStyle(cellStyle);

// 添加数据内容

for (int i = 0; i < list.size(); i++) {
hssfRow = sheet.createRow((int) i + 1);
Map<String, Object> map = list.get(i);

// 创建单元格,并设置值

HSSFCell cell = hssfRow.createCell(0);
cell.setCellValue(map.get("userName") + "");
cell.setCellStyle(cellStyle);

cell = hssfRow.createCell(1);
cell.setCellValue(map.get("content") + "");
cell.setCellStyle(cellStyle);

cell = hssfRow.createCell(2);
cell.setCellValue((Integer) map.get("recommend") == 1 ? "是" : "否");
cell.setCellStyle(cellStyle);

cell = hssfRow.createCell(3);
cell.setCellValue((Integer) map.get("likeNumber"));
cell.setCellStyle(cellStyle);

cell = hssfRow.createCell(4);
cell.setCellValue(DateUtil.dateToStrByFormat(DateUtil.longToDate((Long) map.get("releaseTime")),
DateUtil.LONG_DATE_FORMAT));
cell.setCellStyle(cellStyle);
}

// 返回Excel文件

return workbook;

}
}


导入案例

// 导入功能

(function(){(“#btn-upload”).upload({

// 默认name为file

action : ‘/importExcel’,

onSelect :function(){

},

onComplete : function(response){

alert(response);

}

});

// 表格的导入

@RequestMapping(value = “/importExcel”, method = RequestMethod.POST)

@ResponseBody

public String Import(@RequestParam(“file”) MultipartFile file) {

// 判断文件是否为空

if (file == null) {

return “文件不能为空”;

}

// 获取文件名
String fileName = file.getOriginalFilename();

// 验证文件名是否合格
if (!ExcelImportUtils.validateExcel(fileName)) {
return "文件必须是excel格式!";
}

// 进一步判断文件内容是否为空(即判断其大小是否为0或其名称是否为null)
long size = file.getSize();
if (StringUtils.isEmpty(fileName) || size == 0) {
return "文件内容不能为空";
}

// 批量导入
String message = uploadService.batchImport(fileName, file);

return message;

}


/**

* 上传excel文件到临时目录后并开始解析

*

* @param fileName

* @param file

* @param CrawlConfigRequestName

* @return

*/

public String batchImport(String fileName, MultipartFile mfile) {

InputStream is = null;
try {
is = mfile.getInputStream();
// 根据版本选择创建Workbook的方式
Workbook wb = null;
// 根据文件名判断文件是2003版本还是2007版本
if (ExcelImportUtils.isExcel2007(fileName)) {
wb = new XSSFWorkbook(is);
} else {
wb = new HSSFWorkbook(is);
}
// 根据excel里面的内容读取知识库信息
return readExcelValue(wb);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
}
return "导入出错!请检查数据格式!";
}

/**
* 解析Excel里面的数据
*
* @param wb
* @return
*/
private String readExcelValue(Workbook wb) {

// 错误信息接收器
String errorMsg = "";
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
int totalRows = sheet.getPhysicalNumberOfRows();
// 总列数
int totalCells = 0;
// 得到Excel的列数(前提是有行数),从第二行算起
if (totalRows >= 2 && sheet.getRow(1) != null) {
totalCells = sheet.getRow(1).getPhysicalNumberOfCells();
}
List<CrawlConfigRequest> list = new ArrayList<CrawlConfigRequest>();
CrawlConfigRequest temp;

String br = "<br/>";

// 循环Excel行数,从第二行开始。标题不入库
for (int r = 1; r < totalRows; r++) {
String rowMessage = "";
Row row = sheet.getRow(r);
if (row == null) {
errorMsg += br + "第" + (r + 1) + "行数据有问题,请仔细检查!";
continue;
}
temp = new CrawlConfigRequest();

String officalAppUrl = "";
String meadinBrandId = "";
String officialAppId = "";
// 循环Excel的列
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
if (c == 0) {
meadinBrandId = cell.getStringCellValue().trim();
if (StringUtils.isEmpty(meadinBrandId)) {
rowMessage += "监测对象的ID不能为空;";
}
temp.setMeadinBrandId(Long.parseLong(meadinBrandId));
} else if (c == 1) {
officialAppId = cell.getStringCellValue().trim();
if (StringUtils.isEmpty(officialAppId)) {
rowMessage += "APP_ID不能为空;";
}
temp.setOfficialAppId(Long.parseLong(officialAppId));
;
} else if (c == 2) {
officalAppUrl = cell.getStringCellValue().trim();
if (StringUtils.isEmpty(officalAppUrl)) {
rowMessage += "url地址不能为空;";
}
temp.setOfficalAppUrl(officalAppUrl);
}
} else {
rowMessage += "第" + (c + 1) + "列数据有问题,请仔细检查;";
}
}
// 拼接每行的错误提示
if (!StringUtils.isEmpty(rowMessage)) {
errorMsg += br + "第" + (r + 1) + "行," + rowMessage;
} else {
list.add(temp);
}
}

// 全部验证通过才导入到数据库
if (StringUtils.isEmpty(errorMsg)) {
for (CrawlConfigRequest request : list) {
request.setId(0l);
// 保存到数据库
configService.addOrUpdateConfigInfo(request);
}
errorMsg = "导入成功,共" + list.size() + "条数据!";
}
return errorMsg;
}


}

public class ExcelImportUtils {

/*

* 是否是2003的excel,返回true是2003

*/

public static boolean isExcel2003(String filePath) {

return filePath.matches(“^.+\.(?i)(xls)$”);

}

/*
* :是否是2007的excel,返回true是2007
*/
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}

/**
* 判断文件格式
*/
public String isExcel(String filename) {
if (filename.matches("^.+\\.(?i)(xlsx|xls)$")) {
return "";
}
return "只能上传.xls或.xlsx结尾的文件!";
}

/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public static boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
return false;
}
return true;
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: