package com.myships.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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;
/**
* ExcleTools excle工具类
* @author jinyihao
*
*/
public class ExcleTools {
static String path = "D://";
/**
* 创建文件路径
* @param destFileName 字符串格式的 文件路径
* @return
*/
public static File createFile(String destFileName) {
File file = new File(destFileName);
if (!file.exists()) {
if (destFileName.endsWith(File.separator)) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");
return null;
}
// 判断目标文件所在的目录是否存在
if (!file.getParentFile().exists()) {
System.out.println("目标文件所在目录不存在,准备创建它!");
if (!file.getParentFile().mkdirs()) {
System.out.println("创建目标文件所在目录失败!");
return null;
}
}
try {
if (file.createNewFile()) {
System.out.println("创建单个文件" + destFileName + "成功!");
return file;
} else {
System.out.println("创建单个文件" + destFileName + "失败!");
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage());
}
}
return file;
}
/**
* 获取单元格的值,如果为公式,则获取公式解析后的值(非公式本身)
* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null)
return cellValue;
int cType = cell.getCellType();
try {
switch (cType) {
// 这里会不会有问题?会不会返回null?
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
// 此为XLS内存储的真实的值,XLS不是一个所见即所得的工具,如值为0.8125,如果设置单元格
// 为数值型,且小数位为2位,则见到的为0.81,而实际读取到的值仍为0.8125.此处添加对数值
// 型数据的格式化,以满足获取所见的数值所需;
// (实际上仍存在瑕疵,如设置的小数位为5位,但无法获取其数值类型,故无法取到正确的显示值)
cellValue = cell.getNumericCellValue() + "";
}
break;
case Cell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 是公式,获取公式值
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellValue = Byte.toString(cell.getErrorCellValue());
break;
default:
cellValue = cell.getStringCellValue();
break;
}
} catch (Exception e) {
return null;
}
if (cellValue != null) // 对单元格值取TRIM
cellValue = cellValue.trim();
return cellValue;
}
private static CellStyle getCellStyle(Workbook workbook){
//设置格式
CellStyle cellStyle = workbook.createCellStyle();
//设置边框:
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
return cellStyle;
}
/**
* 导入Excel表格
* @param xlsPath:文件的路径:D://a.xls 支持xls 和xlsx
* @returnList<Map<String, String>>
* @throws IOException
*/
public static List<Map<String, Object>> importExcel(String xlsPath, String[] keys, int RowNum, int cell) {
List<Map<String, Object>> temp = new ArrayList<Map<String, Object>>();
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(xlsPath);
// 根据指定的文件输入流导入Excel从而产生Workbook对象
Workbook wb0 = null;
if (xlsPath.endsWith(".xls")) {
wb0 = new HSSFWorkbook(fileIn);
} else if (xlsPath.endsWith(".xlsx")) {
wb0 = new XSSFWorkbook(fileIn);
} else {
return new ArrayList<Map<String, Object>>();// 格式不对返回,
}
// 获取Excel文档中的第一个表单
Sheet sht0 = wb0.getSheetAt(0);
// 对Sheet中的每一行进行迭代
for (Row r : sht0) {
// 如果当前行的行号(从0开始)未达到2(第三行)则从新循环
if (r.getRowNum() < RowNum) {
continue;
}
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], getCellValue(r.getCell(cell + i)));
}
temp.add(map);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileIn != null) {
try {
fileIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return temp;
}
/*
* (非 Javadoc)导出Excel表格
* @see org.springframework.web.servlet.view.document.AbstractExcelView#
* buildExcelDocument(java.util.Map,
* org.apache.poi.hssf.usermodel.HSSFWorkbook,
* javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
protected static void exportExcelDocument(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
Workbook workbook = getWorkbook(model);
String fileName = (String) model.get("fileName");// 表名
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
// 向哪输出
OutputStream ouputStream = null;
try {
ouputStream = response.getOutputStream();
workbook.write(ouputStream); // 把相应的Excel 工作簿存盘
ouputStream.flush();// 刷新缓冲,将缓冲区中的数据全部取出来
} catch (IOException e) {
// TODO Auto-generated catch block
} finally {
if (ouputStream != null) {
try {
ouputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
@SuppressWarnings("rawtypes")
private static Workbook getWorkbook(Map<String, Object> model) {
Object[] cells = (Object[]) model.get("cells");// 表头
String sheetName = (String) model.get("sheetName");
List lists = (List) model.get("list");// 表数据
Workbook workbook = null;
String fileName = (String) model.get("fileName");// 表名
if (fileName.endsWith(".xls")) {
workbook = new HSSFWorkbook();
} else if (fileName.endsWith(".xlsx")) {
workbook = new XSSFWorkbook();
} else {
return null;
}
Sheet sheet = workbook.createSheet(sheetName);
sheet.setDefaultRowHeight((short) (2 * 256)); // 设置默认行高,表示2个字符的高度
sheet.setDefaultColumnWidth(12); // 设置默认列宽
CellStyle cellStyle = getCellStyle(workbook);
// 首先构造excel表头
Row row = sheet.createRow(0);
for (int i = 0; i < cells.length; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(String.valueOf(cells[i]));
cell.setCellStyle(cellStyle);
}
// 然后构造excel列表数据
int nums = 1;
for (int i = 0; i < lists.size(); i++) {
Map map = (Map) lists.get(i);// 获取数据
row = sheet.createRow(nums);// 添加一行
nums++;
for (int k = 0; k < map.size(); k++) {
Cell cell = row.createCell(k);
cell.setCellValue(map.get(String.valueOf(k + 1)).toString());
cell.setCellStyle(cellStyle);
}
}
return workbook;
}
public static void exportExcelLoaclhost(Map<String, Object> model) {
Workbook workbook = getWorkbook(model);
if (workbook == null) {
System.out.println("文件格式异常,只支持excle文件格式");
return;
}
String fileName = (String) model.get("fileName");// 表名
OutputStream os = null;
try {
File file = createFile(path.concat(fileName));
os = new FileOutputStream(file);
workbook.write(os);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
List<Map<String, Object>> areaInfoList = importExcel("d:/模板.xlsx", new String[] { "no", "qwe" }, 1, 1);
for (Map<String, Object> map : areaInfoList) {
System.out.println(map.get("no") + " " + map.get("qwe"));
}
// List<Map<String, Object>> list = new ArrayList<Map<String,
// Object>>();
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("1", "1");
// map.put("2", "区域:圆");
// list.add(map);
// map = new HashMap<String, Object>();
// map.put("1", "2");
// map.put("2", "区域:矩形");
// list.add(map);
// map = new HashMap<String, Object>();
// map.put("1", "3");
// map.put("2", "区域:多边形");
// list.add(map);
// Map<String, Object> model = new HashMap<String, Object>();
// model.put("cells", new String[] { "序号", "敏感词"});
// model.put("sheetName", "sheet1");
// model.put("fileName", "模板.xlsx");
// model.put("list", list);
// buildExcelLoaclhost(model);
}
}