版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fancheng614/article/details/81453907
一、导入jar
本项目使用Maven管理jar,这里添加POI相关的jar依赖
<!-- POI -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
二、封装代码(类名称POIUtil.java):
导出并下载excel的封装代码:
/**
* @param title
* 工作簿名称
* @param heads
* 表格第一行名称数组
* @param dates
* 要导入表格的数据
* @param url
* 临时存放excel文件的文件夹
* 导出excel
*/
private static void exportExcel(String title, String[] heads,
List<Map<String, String>> dates, String url) {
// 新建excel报表
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
// 添加一个sheet名称
HSSFSheet hssfSheet = hssfWorkbook.createSheet(title);
//设置单元格样式
HSSFCellStyle style = hssfWorkbook.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER); //水平居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
/*
* 设定合并单元格区域范围 firstRow 0-based lastRow 0-based firstCol 0-based lastCol
* 0-based
*/
CellRangeAddress cra = new CellRangeAddress(0, 0, 0, heads.length - 1);
// 在sheet里增加合并单元格
hssfSheet.addMergedRegion(cra);
HSSFRow row = hssfSheet.createRow(0);
HSSFCell cell_1 = row.createCell(0);
cell_1.setCellValue(title);
cell_1.setCellStyle(style); //设置样式
HSSFRow hssfRow = hssfSheet.createRow(1);
for (int i = 0; i < heads.length; i++) {
HSSFCell hssfCell = hssfRow.createCell(i);
hssfCell.setCellValue(heads[i]);
}
// 循环将list里面的值取出来放进excel中
for (int i = 0; i < dates.size(); i++) {
HSSFRow hssfRow1 = hssfSheet.createRow(i + 2);
int j = 0;
Iterator<Map.Entry<String, String>> it = dates.get(i).entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
HSSFCell hssfCell = hssfRow1.createCell(j);
hssfCell.setCellValue(entry.getValue());
j++;
}
}
FileOutputStream fout = null;
try {
// 用流将其写到D盘
fout = new FileOutputStream(url);
hssfWorkbook.write(fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param path
* 临时存放excel文件路径
* @param title
* 工作簿名称
* @param heads
* 表格第一行名称数组
* @param dates
* 要写入表格的数据
* 下载excel
* */
public static void download(String path, HttpServletResponse response,
String title, String[] heads, List<Map<String, String>> dates) {
exportExcel(title, heads, dates, path);
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
toClient.write(buffer);
toClient.flush();
toClient.close();
// 删除d:/test文件夹下面临时存放的文件
File file2 = new File(path);
file2.delete();
} catch (IOException ex) {
ex.printStackTrace();
}
}
读取excel的封装代码(这里兼容了xls和xlsx):
private final static String xls = "xls";
private final static String xlsx = "xlsx";
/**
* 读入excel文件,解析后返回
*
* @param file
* @throws IOException
*/
public static List<String[]> readExcel(MultipartFile file)
throws IOException {
// 检查文件
checkFile(file);
// 获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
// 创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<String[]> list = new ArrayList<String[]>();
if (workbook != null) {
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
// 获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if (sheet == null) {
continue;
}
// 获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
// 获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
// 循环除了第一行的所有行
for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
// 获得当前行
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
// 获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
// 获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
// 循环当前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
}
return list;
}
/**
* @param file
* @throws IOException
* 检查传过来的文件是不是excel文件
*/
public static void checkFile(MultipartFile file) throws IOException {
// 判断文件是否存在
if (null == file) {
throw new FileNotFoundException("文件不存在!");
}
// 获得文件名
String fileName = file.getOriginalFilename();
// 判断文件是否是excel文件
if (!fileName.endsWith(xls) && !fileName.endsWith(xlsx)) {
throw new IOException(fileName + "不是excel文件");
}
}
/**
* @param file
* @return
* 创建并返回一个workBook(兼容xls和xlsx)
*/
public static Workbook getWorkBook(MultipartFile file) {
// 获得文件名
String fileName = file.getOriginalFilename();
// 创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
// 获取excel文件的io流
InputStream is = file.getInputStream();
// 根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if (fileName.endsWith(xls)) {
// 2003
workbook = new HSSFWorkbook(is);
} else if (fileName.endsWith(xlsx)) {
// 2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
}
return workbook;
}
/**
* @param cell
* @return
* 根据excel表格中的数据类型和数据值返回相对应的数据值
*/
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
// 把数字当成String来读,避免出现1读成1.0的情况
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cell.setCellType(Cell.CELL_TYPE_STRING);
}
// 判断数据的类型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: // 数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: // 字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: // 公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
三、调用封装代码:
本项目使用的是SpringMVC,调用封装代码在一下的Controller中调用。可以根据自己的需要就行进一步的封装。
/**
* @param file
* @param model
* @return
* 读取excel并将excel中的数据存进数据库
*/
@RequestMapping("upload")
public String upload(@RequestParam("file")MultipartFile file,Model model){
try {
List<String[]> list = POIUtil.readExcel(file);
for (String[] strings : list) {
for (int i = 0; i < strings.length; i++) {
//这里可以获取excel的数据,然后将数据添加进数据库里面
System.out.print(strings[i]+"\t");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
model.addAttribute("success", "上传成功");
return "index";
}
/**
* @param model
* @param response
* @return
* 导出excel报表
*/
@RequestMapping("export")
public String exportExcel(Model model,HttpServletResponse response){
String title = "哈哈";
String[] heads = {"ID","Name","Pass"};
List<Map<String, String>> dates = new ArrayList<Map<String,String>>();
for (int i = 0; i < 10; i++) {
//这里使用LinkedHashMap来保证map中元素的顺序
Map<String, String> map = new LinkedHashMap<String,String>();
map.put("ID", String.valueOf(i+1));
map.put("Name", "name"+(i+1));
map.put("Pass", "pass"+(i+1));
dates.add(map);
}
POIUtil.download("D:/111AAAmeng/haha.xls", response, title, heads, dates);
model.addAttribute("success", "导出成功");
//这里应该采用ajax而不能返回页面,否则报错;返回null就行了(这样可以下载excel表格并且不报错)
return null;
}