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);
}
}