Excel POI 匯入匯出(支援大資料量快速匯出)
POI 匯入匯出功能,引用jar包是關鍵,maven依賴支援3.17版.
介紹:
首先,理解一下一個Excel的檔案的組織形式,一個Excel檔案對應於一個workbook(HSSFWorkbook),一個workbook可以有多個sheet(頁/表)(HSSFSheet)組成,一個sheet是由多個row(行)(HSSFRow)組成,一個row是由多個cell(單元格)(HSSFCell)組成。
1、用HSSFWorkbook開啟或者建立“Excel檔案物件
2、用HSSFWorkbook物件返回或者建立Sheet物件
3、用Sheet物件返回行物件,用行物件得到Cell物件
4、對Cell物件讀寫
maven 依賴:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>
mvc 依賴:
poi-3.7-20101029.jar
poi-3.9.jar
poi-ooxml-3.9.jar
poi-ooxml-schemas-3.9.jar
ExcelUtil.java (匯入匯出工能封裝)
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.poi.common.usermodel.HyperlinkType; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFHyperlink; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.*; /** * Created by cdw on 2018/04/19. * * Apache POI操作Excel物件 HSSF:操作Excel 2007之前版本(.xls)格式,生成的EXCEL不經過壓縮直接匯出 * XSSF:操作Excel 2007及之後版本(.xlsx)格式,記憶體佔用高於HSSF SXSSF:從POI3.8 * beta3開始支援,基於XSSF,低記憶體佔用,專門處理大資料量(建議)。 * * 注意: 值得注意的是SXSSFWorkbook只能寫(匯出)不能讀(匯入) * * 說明: .xls格式的excel(最大行數65536行,最大列數256列) .xlsx格式的excel(最大行數1048576行,最大列數16384列) * 這裡引用的是阿里的json包,也可以自行轉換成net.sf.json.JSONArray net.sf.json.JSONObject */ public class ExcelUtil { private final static String Excel_2003 = ".xls"; // 2003 版本的excel private final static String Excel_2007 = ".xlsx"; // 2007 版本的excel public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss"; // 預設日期格式(型別為Date即可轉換) public static final int DEFAULT_COLUMN_WIDTH = 17; // 預設列寬 /** * 匯入Excel * * @param file * 輸入檔案流 */ public static List<List<Object>> importExcel(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception { String fileName = file.getOriginalFilename(); String xls = fileName.substring(fileName.lastIndexOf('.')); if (Excel_2003.equals(xls) || Excel_2007.equals(xls)) { return ExcelUtil.getImportExcel(file); } else { // 匯入格式不正確 System.out.println("匯入格式不正確:匯入失敗!"); } return null; } /** * 匯出Excel * * @param titleList * 表格頭資訊集合 * @param dataArray * 資料陣列 * @param os * 檔案輸出流 */ public static void exportExcel(ArrayList<LinkedHashMap> titleList, JSONArray dataArray, OutputStream os) throws Exception { ExcelUtil.getExportExcel(titleList, dataArray, os); } /** * 匯入Excel * * @param file * 匯入檔案流物件 */ private static List<List<Object>> getImportExcel(MultipartFile file) throws Exception { ImportExcelUtil util = new ImportExcelUtil(); String fileName = file.getOriginalFilename(); InputStream inputStream = file.getInputStream(); // 將匯入的Excel資料轉換成list集合 List<List<Object>> excelLists = util.getBankListByExcel(inputStream, fileName); // 獲取工作模板行資料物件 // HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(inputStream)); // 或 // Workbook workbook = util.getWorkbook(inputStream, fileName); // // for (int i = 0; i < excelLists.size(); i++) { // 迴圈行 // List<Object> list = excelLists.get(i); // 獲取行級列集合 // for (int j = 0; j < list.size(); j++) { // System.out.println("獲取" + i + "行級" + j + "列的值:" + list.get(j)); // } // } // // for (List<Object> excelList : excelLists) { // 迴圈行 // for (Object obj : excelList) { // 迴圈列 // // 獲取行級列的值 // } // } // // for (Sheet rows : workbook) { // 迴圈行 // for (Row row : rows) { // 迴圈列 // // 獲取行級列的值 // } // } return excelLists; } /** * 匯出Excel * * @param titleList * 表格頭資訊集合 * @param dataArray * 資料陣列 * @param os * 檔案輸出流 */ private static void getExportExcel(ArrayList<LinkedHashMap> titleList, JSONArray dataArray, OutputStream os) throws Exception { String datePattern = DEFAULT_DATE_PATTERN; int minBytes = DEFAULT_COLUMN_WIDTH; /** * 宣告一個工作薄 */ SXSSFWorkbook workbook = new SXSSFWorkbook(1000);// 大於1000行時會把之前的行寫入硬碟 workbook.setCompressTempFiles(true); // 表頭1樣式 CellStyle title1Style = workbook.createCellStyle(); title1Style.setAlignment(HorizontalAlignment.CENTER);// 水平居中 title1Style.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中 Font titleFont = workbook.createFont();// 字型 titleFont.setFontHeightInPoints((short) 20); titleFont.setBold(true); titleFont.setFontHeight((short) 700); title1Style.setFont(titleFont); // 表頭2樣式 CellStyle title2Style = workbook.createCellStyle(); title2Style.setAlignment(HorizontalAlignment.CENTER); title2Style.setVerticalAlignment(VerticalAlignment.CENTER); title2Style.setBorderTop(BorderStyle.THIN);// 上邊框 title2Style.setBorderRight(BorderStyle.THIN);// 右 title2Style.setBorderBottom(BorderStyle.THIN);// 下 title2Style.setBorderLeft(BorderStyle.THIN);// 左 Font title2Font = workbook.createFont(); title2Font.setUnderline((byte) 1); title2Font.setColor(HSSFColor.BLUE.index); title2Style.setFont(title2Font); // head樣式 CellStyle headerStyle = workbook.createCellStyle(); headerStyle.setAlignment(HorizontalAlignment.CENTER); headerStyle.setVerticalAlignment(VerticalAlignment.CENTER); headerStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);// 設定顏色 headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 前景色純色填充 headerStyle.setBorderTop(BorderStyle.THIN); headerStyle.setBorderRight(BorderStyle.THIN); headerStyle.setBorderBottom(BorderStyle.THIN); headerStyle.setBorderLeft(BorderStyle.THIN); Font headerFont = workbook.createFont(); headerFont.setFontHeightInPoints((short) 12); headerFont.setBold(true); // 是否加粗 headerFont.setFontHeight((short) 500); // 字型大小 headerStyle.setFont(headerFont); // 單元格樣式 CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); cellStyle.setBorderTop(BorderStyle.THIN); cellStyle.setBorderRight(BorderStyle.THIN); cellStyle.setBorderBottom(BorderStyle.THIN); cellStyle.setBorderLeft(BorderStyle.THIN); Font cellFont = workbook.createFont(); cellFont.setBold(false); // 是否加粗 cellFont.setFontHeight((short) 300); // 字型大小 cellStyle.setFont(cellFont); String title1 = (String) titleList.get(0).get("title1"); String title2 = (String) titleList.get(0).get("title2"); LinkedHashMap<String, String> headMap = titleList.get(1); /** * 生成一個(帶名稱)表格 */ SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet(title1); sheet.createFreezePane(0, 3, 0, 3);// (單獨)凍結前三行 /** * 生成head相關資訊+設定每列寬度 */ int[] colWidthArr = new int[headMap.size()];// 列寬陣列 String[] headKeyArr = new String[headMap.size()];// headKey陣列 String[] headValArr = new String[headMap.size()];// headVal陣列 int i = 0; for (Map.Entry<String, String> entry : headMap.entrySet()) { headKeyArr[i] = entry.getKey(); headValArr[i] = entry.getValue(); int bytes = headKeyArr[i].getBytes().length; colWidthArr[i] = bytes < minBytes ? minBytes : bytes; sheet.setColumnWidth(i, colWidthArr[i] * 256);// 設定列寬 i++; } /** * 遍歷資料集合,產生Excel行資料,除去 title + head 資料起始行為0,賦值為3(即第四行起) */ int rowIndex = 0; for (Object obj : dataArray) { // 生成title+head資訊 if (rowIndex == 0) { SXSSFRow title1Row = (SXSSFRow) sheet.createRow(0);// title1行 title1Row.createCell(0).setCellValue(title1); title1Row.getCell(0).setCellStyle(title1Style); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));// 合併單元格 SXSSFRow title2Row = (SXSSFRow) sheet.createRow(1);// title2行 title2Row.createCell(0).setCellValue(title2); CreationHelper createHelper = workbook.getCreationHelper(); XSSFHyperlink hyperLink = (XSSFHyperlink) createHelper.createHyperlink(HyperlinkType.URL); hyperLink.setAddress(title2); title2Row.getCell(0).setHyperlink(hyperLink);// 新增超連結 title2Row.getCell(0).setCellStyle(title2Style); sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, headMap.size() - 1));// 合併單元格 SXSSFRow headerRow = (SXSSFRow) sheet.createRow(2);// head行 for (int j = 0; j < headValArr.length; j++) { headerRow.createCell(j).setCellValue(headValArr[j]); headerRow.getCell(j).setCellStyle(headerStyle); } rowIndex = 3; } JSONObject jo = (JSONObject) JSONObject.toJSON(obj); // 生成資料 SXSSFRow dataRow = (SXSSFRow) sheet.createRow(rowIndex);// 建立行 for (int k = 0; k < headKeyArr.length; k++) { SXSSFCell cell = (SXSSFCell) dataRow.createCell(k);// 建立單元格 Object o = jo.get(headKeyArr[k]); String cellValue = ""; if (o == null) { cellValue = ""; } else if (o instanceof Date) { cellValue = new SimpleDateFormat(datePattern).format(o); } else if (o instanceof Float || o instanceof Double) { cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString(); } else { cellValue = o.toString(); } cell.setCellValue(cellValue); cell.setCellStyle(cellStyle); } rowIndex++; } // // 另外一種匯出方式 // HSSFWorkbook workbook = new HSSFWorkbook(); // HSSFSheet sheet = workbook.createSheet("測試表"); // HSSFRow titleRow = sheet.createRow(0); // sheet.setColumnWidth(titleRow.createCell(0).getColumnIndex(), 256 * 20); // titleRow.createCell(0).setCellValue("名稱"); // sheet.setColumnWidth(titleRow.createCell(1).getColumnIndex(), 256 * 20); // titleRow.createCell(1).setCellValue("狀態(0-已生成,1-待生成)"); // // 設定應用型別,以及編碼 // response.setContentType("application/msexcel;charset=utf-8"); // response.setHeader("Content-Disposition", "filename=" + new String("測試表.xls".getBytes("gb2312"), "iso8859-1")); // workbook.write(output); // output.flush(); // output.close(); try { workbook.write(os); os.flush();// 重新整理此輸出流並強制將所有緩衝的輸出位元組寫出 os.close();// 關閉流 workbook.dispose();// 釋放workbook所佔用的所有windows資源 } catch (IOException e) { e.printStackTrace(); } } }
ImportExcelUtil.java (Excel資料轉換類)
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by cdw on 2018/04/19.
*
* 轉換類
*
* 說明: .xls格式的excel(最大行數65536行,最大列數256列) .xlsx格式的excel(最大行數1048576行,最大列數16384列)
*/
public class ImportExcelUtil {
private final static String Excel_2003 = ".xls"; //2003 版本的excel
private final static String Excel_2007 = ".xlsx"; //2007 版本的excel
/**
* @param in
* @param fileName
*
* @return
*/
public List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception {
List<List<Object>> list = null;
//建立Excel工作簿
Workbook work = this.getWorkbook(in, fileName);
if (work == null) {
throw new Exception("建立Excel工作簿為空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//遍歷Excel中的所有sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
//遍歷當前sheet中的所有行
//int totalRow = sheet.getPhysicalNumberOfRows();//如果excel有格式,這種方式取值不準確
int totalRow = sheet.getPhysicalNumberOfRows();
for (int j = sheet.getFirstRowNum(); j < totalRow; j++) {
row = sheet.getRow(j);
if (!isRowEmpty(row)) {
//if(row != null && !"".equals(row)) {
//獲取第一個單元格的資料是否存在
Cell fristCell = row.getCell(0);
if (fristCell != null) {
//遍歷所有的列
List<Object> li = new ArrayList<Object>();
//int totalColum = row.getLastCellNum();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
String callCal = this.getCellValue(cell) + "";
li.add(callCal);
}
list.add(li);
}
} else if (isRowEmpty(row)) {
continue;
}
}
}
in.close();
return list;
}
/**
* 判斷行是否為空
*
* @param row
*
* @return
*/
public static boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
return false;
}
return true;
}
/**
* 描述:根據檔案字尾,自動適應上傳檔案的版本
*
* @param inStr,fileName
*
* @return
*
* @throws Exception
*/
public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
Workbook work = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (Excel_2003.equals(fileType)) {
work = new HSSFWorkbook(inStr);//2003 版本的excel
} else if (Excel_2007.equals(fileType)) {
work = new XSSFWorkbook(inStr);//2007 版本的excel
} else {
throw new Exception("解析檔案格式有誤!");
}
return work;
}
/**
* 描述:對錶格中數值進行格式化
*
* @param cell
*
* @return
*/
public Object getCellValue(Cell cell) {
/*Object value = null;
DecimalFormat df1 = new DecimalFormat("0.00");//格式化number,string字元
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");//日期格式化
DecimalFormat df2 = new DecimalFormat("0.00");//格式化數字
if(cell !=null && !"".equals(cell)) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())) {
value = df1.format(cell.getNumericCellValue());
}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
value = sdf.format(cell.getDateCellValue());
}else if(HSSFDateUtil.isCellDateFormatted(cell)){
Date date = cell.getDateCellValue();
value = sdf.format(date);
}
else {
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
}
return value;*/
String result = new String();
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA: //Excel公式
try {
result = String.valueOf(cell.getNumericCellValue());
} catch (IllegalStateException e) {
result = String.valueOf(cell.getRichStringCellValue());
}
break;
case HSSFCell.CELL_TYPE_NUMERIC:// 數字型別
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式
SimpleDateFormat sdf;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
result = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 處理自定義日期格式:m月d日(通過判斷單元格的格式id解決,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("M月d日");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
result = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 單元格設定成常規
if (temp.equals("General")) {
format.applyPattern("#.##");
}
result = format.format(value);
}
break;
case HSSFCell.CELL_TYPE_STRING:// String型別
result = cell.getRichStringCellValue().toString();
break;
case HSSFCell.CELL_TYPE_BLANK:
result = "";
default:
result = "";
break;
}
return result;
}
public String getFormat(String str) {
if(str.equals("null")) {
str="";
return str;
}else{
return str;
}
}
public Integer getFormats(Integer str) {
if(str==null) {
str=0;
return str;
}else{
return str;
}
}
/**
* 獲取字串中的數字訂單號、數字金額等,如從"USD 374.69"中獲取到374.69、從“交易單號:123456789”獲取到123456789
*
* @return
*/
public static String getFormatNumber(String str){
str = str.trim();
Pattern p = Pattern.compile("[0-9]");
int indexNum = 0;
int lenght = str.length();
String num = "";
for(int i=0;i<lenght;i++){
num += str.charAt(i);
Matcher m = p.matcher(num);
if(m.find()){
indexNum = i;
break;
}
}
String formatNumber = str.substring(indexNum,lenght);
return formatNumber;
}
}
匯出功能引用方法:
// 匯出
@ResponseBody
@RequestMapping(value = "/excelOut", method = RequestMethod.GET)
public String excelOut(HttpServletRequest request, HttpServletResponse response) {
try {
// 獲得輸出流
OutputStream output = response.getOutputStream();
ArrayList<LinkedHashMap> titleList = new ArrayList<LinkedHashMap>();
LinkedHashMap<String, String> titleMap = new LinkedHashMap<String, String>();
// title1設定標題,key固定
titleMap.put("title1", "測試匯出表");
titleMap.put("title2", "測試匯出錶鏈接");
LinkedHashMap<String, String> headMap = new LinkedHashMap<String, String>();
headMap.put("ranking", "序號");
headMap.put("posterName", "名稱");
headMap.put("status", "狀態");
titleList.add(titleMap);
titleList.add(headMap);
// 資料集合,下面的欄位名必須和上面的map物件key或者資料實體類引數保持一致
List<JSONObject> objects = new ArrayList<JSONObject>();
for (int i = 0; i < 20; i++) {
JSONObject result = new JSONObject();
result.put("ranking", "value" + i);
result.put("posterName", "value" + i);
result.put("status", "value" + i);
objects.add(result);
}
JSONArray objectsList = JSONArray.parseArray(objects.toString());
// 設定應用型別,以及編碼
response.setContentType("application/msexcel;charset=utf-8");
response.setHeader("Content-Disposition",
"filename=" + new String("測試匯出表.xlsx/測試匯出表.xls".getBytes("gb2312"), "iso8859-1"));
ExcelUtil.exportExcel(titleList, objectsList, output);
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
匯入功能引用方法:
// 匯入
@ResponseBody
@RequestMapping(value = "/excelIn", method = RequestMethod.POST)
public String excelIn(@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletResponse response) {
try {
List<List<Object>> lists = ExcelUtil.importExcel(file);
System.out.println("匯入結果:" + lists.toString());
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
匯入功能前臺引用檔案:
檔案引用
jquery.min.js
jquery.form.js
匯入功能前臺處理方法:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<head>
<title>匯入匯出-匯入頁面</title>
<script src="${pageContext.request.contextPath}/js/jquery.min.js?v=2.1.4"></script>
<script src="${pageContext.request.contextPath}/js/jquery.form.js?v=2.1.4"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js?v=3.3.6"></script>
</head>
<body>
<!--匯入-->
<form action="/user/excelIn" enctype="multipart/form-data" method="post" id="fileForm" name="fileForm">
<input type="file" id="file" name="file" accept="application/vnd.ms-excel" onchange="chooseFile(this.value)">
<input type="button" value="選擇檔案" class="filebtn" id="filebtn"/>
<input type="text" id="filetxt" class="filetxt" readonly>
<input type="submit" value="上傳Excel" id="importbtn" class="importbtn"/>
</form>
<script>
function exportExcel() {
// 匯出介面地址
window.location.href = "http://127.0.0.1:8081/user/excelIn";
}
//觸發file change事件
function chooseFile(path) {
if (path) {
$('#filetxt').val(path);
} else {
$('#filetxt').attr('readonly', true);
}
}
$(function () {
$("#fileForm").ajaxForm({
beforeSubmit: function () {
// 表單資料提交之前的操作
},
success: function (obj) {
console.log("匯入結果:" + obj);
},
error: function (msg) {
console.log("匯入錯誤:" + msg);
}
});
});
</script>
</body>
</html>
示例:
匯入結果:[[測試匯出表], [測試匯出錶鏈接], [序號, 名稱, 狀態], [value0, value0, value0], [value1, value1, value1], [value2, value2, value2], [value3, value3, value3], [value4, value4, value4], [value5, value5, value5], [value6, value6, value6], [value7, value7, value7], [value8, value8, value8], [value9, value9, value9], [value10, value10, value10], [value11, value11, value11], [value12, value12, value12], [value13, value13, value13], [value14, value14, value14], [value15, value15, value15], [value16, value16, value16], [value17, value17, value17], [value18, value18, value18], [value19, value19, value19]]
匯出結果:
以上就是完整的匯入匯出功能,支援大資料量快速匯出,匯入.
轉載請註明出處!