起先,以爲實現導入導出的是js插件。後來瞭解到原來我大java就能操作excel文件。
java操作excel文件還是比較簡單的,不過要導入兩個包(使用maven)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
需要注意的是excel 2003和excel 2007及以上的文件格式是不一樣的,上段代碼中poi就是操作excel 2003的HSSFWorkbook(HSSF開頭), poi-ooxml是操作excel 2007及以上的XSSF開頭的類。
話不多說,直接上代碼:
1. 先寫個判斷文件類型的工具類:
public class CEVUtil {
/**
* 依據後綴名判斷讀取的是否爲Excel文件
* @param filePath
* @return
*/
public static boolean isExcel(String filePath){
if(filePath.matches("^.+\\.(?i)(xls)$")||filePath.matches("^.+\\.(?i)(xlsx)$")){
return true;
}
return false;
}
/**
* 檢查文件是否存在
*/
public static boolean fileExist(String filePath){
if(filePath == null || filePath.trim().equals("")) return false;
File file = new File(filePath);
if (file == null || !file.exists()){
return false;
}
return true;
}
/**
* 依據內容判斷是否爲excel2003及以下
*/
public static boolean isExcel2003(String filePath){
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
if(POIFSFileSystem.hasPOIFSHeader(bis)) {
System.out.println("Excel版本爲excel2003及以下");
return true;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return false;
}
/**
* 依據內容判斷是否爲excel2007及以上
*/
public static boolean isExcel2007(String filePath){
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
if(POIXMLDocument.hasOOXMLHeader(bis)) {
System.out.println("Excel版本爲excel2007及以上");
return true;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return false;
}
}
2. 操作excel的類
public class FileController {
/** 錯誤信息 */
private String errorInfo;
/**
* 驗證EXCEL文件是否合法
*/
public boolean validateExcel(String filePath){
/**判斷文件名是否爲空或者文件是否存在 */
if(!CEVUtil.fileExist(filePath)){
errorInfo = "文件不存在";
return false;
}
/**檢查文件是否是Excel格式的文件 */
if (!CEVUtil.isExcel(filePath)) {
errorInfo = "文件名不是excel格式";
return false;
}
return true;
}
/**
* @描述:根據文件名讀取excel文件
*/
public List<List<String>> read(String filePath){
List<List<String>> dataLst = new ArrayList<List<String>>();
InputStream is = null;
try{
/** 驗證文件是否合法 */
if (!validateExcel(filePath)){
return null;
}
/** 判斷文件的類型,是2003還是2007 */
boolean isExcel2003 = true;
if (CEVUtil.isExcel2007(filePath)){
isExcel2003 = false;
}
/** 調用本類提供的根據流讀取的方法 */
is = new FileInputStream(new File(filePath));
Workbook wb = null;
if (isExcel2003){
wb = new HSSFWorkbook(is);
}else{
wb = new XSSFWorkbook(is);
}
dataLst = read(wb);
is.close();
}catch (IOException e){
e.printStackTrace();
}catch (Exception ex){
ex.printStackTrace();
}finally{
if (is != null){
try{
is.close();
}catch (IOException e){
is = null;
e.printStackTrace();
}
}
}
return dataLst;
}
/**
* @描述:讀取數據
*/
private List<List<String>> read(Workbook wb){
List<List<String>> dataLst = new ArrayList<List<String>>();
/**得到總的shell */
int sheetAccount = wb.getNumberOfSheets();
/** 得到第一個shell(第一頁) */
Sheet sheet = wb.getSheetAt(0);
/** 得到Excel的行數 */
int rowCount = sheet.getPhysicalNumberOfRows();
/** 也可以通過得到最後一行數*/
int lastRowNum = sheet.getLastRowNum();
/** 循環Excel的行 */
for (int r = 0; r < rowCount; r++){
Row row = sheet.getRow(r);
if (row == null){
continue;
}
List<String> rowLst = new ArrayList<String>();
/** 循環Excel的列 */
for (int c = 0; c < row.getPhysicalNumberOfCells(); c++){
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell){
// 以下是判斷數據的類型
switch (cell.getCellType()){
//XSSFCell可以達到相同的效果
case HSSFCell.CELL_TYPE_NUMERIC: // 數字
double d = cell.getNumericCellValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {//日期類型
// Date date = cell.getDateCellValue();
Date date = HSSFDateUtil.getJavaDate(d);
cellValue =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}else{//數值類型
cellValue = cell.getNumericCellValue()+"";
}
cellValue = cell.getDateCellValue() + "";
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知類型";
break;
}
}
System.out.print(cellValue +"\t");
rowLst.add(cellValue);
}
System.out.println();
dataLst.add(rowLst);
}
return dataLst;
}
// -----------------------------------向excel寫入數據
// 標題字體
private HSSFFont titleFont = null;
// private XSSFFont titleFont = null; //2007格式
// 標題樣式
private HSSFCellStyle titleStyle = null;
// private XSSFCellStyle titleStyle = null;//2007格式
// 行信息內容樣式
private HSSFCellStyle contentStyle = null;
// private XSSFCellStyle contentStyle = null;//2007格式
/** 寫excel文件
* @throws IOException
*/
public void writeExcel(String[] titleStrs,List<String[]> contentList,String filename) throws IOException{
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\javaloveiphone\\Desktop\\example.xls");
/*
* severlet響應生成excel文件
* HttpServletResponse response
*
* // 文件標題
* String head = new String(filename.getBytes("GB2312"), "ISO-8859-1");
* response.reset();
* response.setContentType("application/vnd.ms-excel");
* response.addHeader("Content-Disposition", "attachment; filename="+ head + ".xls");
*
* HSSFWorkbook wb = new HSSFWorkbook();
* 。。。。。
*
* java.io.OutputStream os = response.getOutputStream();
* wb.write(os);
* os.close();
*
*/
HSSFWorkbook wb = new HSSFWorkbook();// 創建新HSSFWorkbook對象
// XSSFWorkbook wb = new XSSFWorkbook();//2007格式
setExcelStyle(wb);//執行樣式初始化
HSSFSheet sheet = wb.createSheet(filename);// 創建新的sheet對象
// XSSFSheet sheet = wb.createSheet(filename);//2007格式
HSSFRow titleRow = sheet.createRow((short) 0);//創建第一行
// XSSFRow titleRow = sheet.createRow((short) 0);//2007格式
// titleRow.setHeight((short)300);//設置行高,設置太小可能被隱藏看不到
titleRow.setHeightInPoints(20);//20像素
int titleCount = titleStrs.length;// 列數
// 寫標題
for (int k = 0; k < titleCount; k++) {
HSSFCell cell = titleRow.createCell((short) k); // 新建一個單元格
// XSSFCell cell = titleRow.createCell((short) k); //2007格式
// cell.setEncoding(HSSFCell.ENCODING_UTF_16); // 中文字符集轉換
cell.setCellStyle(titleStyle);//設置標題樣式
// cell.setCellValue(new HSSFRichTextString(titleStrs[k])); // 爲單元格賦值
// cell.setCellValue(wb.getCreationHelper().createRichTextString(""));
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(titleStrs[k]);
sheet.setColumnWidth((short)k, (short)5000);//設置列寬
}
int contentCount = contentList.size();//總的記錄數
// 寫內容
for (int i = 0; i < contentCount; i++) {
String [] contents = contentList.get(i);
HSSFRow row = sheet.createRow((short)(i + 1)); // 新建一行
// XSSFRow row = sheet.createRow((short)(i + 1)); // //2007格式
for (int j = 0; j < titleCount; j++) {
HSSFCell cell = row.createCell((short) j); // 新建一個單元格
// XSSFCell cell = row.createCell((short) j); // //2007格式
cell.setCellStyle(contentStyle);//設置內容樣式
if (contents[j] == null || contents[j].equals("null")) {
contents[j] = "";
}
//格式化日期
if(j == 2){
HSSFCellStyle style = wb.createCellStyle();
// XSSFCellStyle style = wb.createCellStyle();//2007格式
style.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
// cell.setCellValue(new Date());
// cell.setCellValue(Calendar.getInstance());
cell.setCellValue(contents[j]);
cell.setCellStyle(style);
}else{
cell.setCellValue(new HSSFRichTextString(contents[j]));
}
}
}
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
/** 樣式初始化*/
public void setExcelStyle(HSSFWorkbook workBook){
// 設置列標題字體,樣式
titleFont = workBook.createFont();
titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 標題列樣式
titleStyle = workBook.createCellStyle();
titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 設置邊框
titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
titleStyle.setFont(titleFont);
// 內容列樣式
contentStyle = workBook.createCellStyle();
contentStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
contentStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
contentStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
contentStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
contentStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
contentStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
}
}