html:
<li>
<span>
上 傳:
</span>
<span class="input">
<input type="file" id="upfile" name="upfile" placeholder="" />
</span>
<button onclick="importExp();">
導入
</button>
<span>
格式:.xls
</span>
</li>
js:
//導入文件
function importExp() {
var formData = new FormData();
var name = $("#upfile").val();
formData.append("file", $("#upfile")[0].files[0]);
formData.append("name", name);
$.ajax({
url: '#springUrl('')/summary/importExp',
type: 'POST',
async: false,
data: formData,
// 告訴jQuery不要去處理髮送的數據
processData: false,
// 告訴jQuery不要去設置Content-Type請求頭
contentType: false,
beforeSend: function() {
console.log("正在進行,請稍候");
},
success: function(responseStr) {
if (responseStr == "01") {
alert("導入成功");
} else {
alert("導入失敗");
}
}
});
}
controller:
@RequestMapping("/importExp")
@ResponseBody
public String importExp(@RequestParam("file") MultipartFile file, HttpServletRequest request){
// 判斷文件是否爲空
String flag = "02";//上傳標誌
if (!file.isEmpty()) {
try {
String originalFilename = file.getOriginalFilename();//原文件名字
InputStream is = file.getInputStream();//獲取輸入流
flag = summaryExpServiceImpl.writeExelData(is);
// 轉存文件
//file.transferTo(new File(filePath));
} catch (Exception e) {
flag="03";//上傳出錯
e.printStackTrace();
}
}
return flag;
}
service:
/**
* 寫入
* @param is
*/
public String writeExelData(InputStream is){
List<List<String>> list = readExcelContent(is);
for (int i=0,j=list.size();i<j;i++){
List<String> row = list.get(i);
ExpInfoSummary expInfoSummary = new ExpInfoSummary();
expInfoSummary.setOrgName(row.get(0));
expInfoSummary.setSiteName(row.get(1));
expInfoSummary.setProductCode(row.get(2));
expInfoSummary.setProductName(row.get(3));
expInfoSummary.setProductNum(row.get(4));
expInfoSummary.setProductPrice(Double.valueOf(row.get(5)));
expInfoSummary.setProductState(row.get(6));
pool.getSqlSession("psEpfSqlSession").selectList("com.jd.ps.data.epf.mapper.expInfoSummary.insertExp", expInfoSummary);
}
return "01";
}
/**
* 讀取Excel數據內容
* @param is
* @return Map 包含單元格數據內容的Map對象
*/
public List<List<String>> readExcelContent(InputStream is) {
List<List<String>> content = new ArrayList<List<String>>();
POIFSFileSystem fs;
HSSFWorkbook wb;
HSSFSheet sheet;
HSSFRow row;
String str = "";
try {
fs = new POIFSFileSystem(is);
wb = new HSSFWorkbook(fs);
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文內容應該從第二行開始,第一行爲表頭的標題
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
List<String> list = new ArrayList<String>();
while (j < colNum) {
// 每個單元格的數據內容用"-"分割開,以後需要時用String類的replace()方法還原數據
// 也可以將每個單元格的數據設置到一個javabean的屬性中,此時需要新建一個javabean
// str += getStringCellValue(row.getCell((short) j)).trim() +
// "-";
str = getCellFormatValue(row.getCell((short) j)).trim();
list.add(str);
j++;
}
content.add(list);
str = "";
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
/**
* 根據HSSFCell類型設置數據
* @param cell
* @return
*/
private String getCellFormatValue(HSSFCell cell) {
String cellvalue = "";
if (cell != null) {
// 判斷當前Cell的Type
switch (cell.getCellType()) {
// 如果當前Cell的Type爲NUMERIC
case HSSFCell.CELL_TYPE_NUMERIC:
case HSSFCell.CELL_TYPE_FORMULA: {
// 判斷當前的cell是否爲Date
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// 如果是Date類型則,轉化爲Data格式
//方法1:這樣子的data格式是帶時分秒的:2011-10-12 0:00:00
//cellvalue = cell.getDateCellValue().toLocaleString();
//方法2:這樣子的data格式是不帶帶時分秒的:2011-10-12
Date date = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cellvalue = sdf.format(date);
}
// 如果是純數字
else {
// 取得當前Cell的數值
cellvalue = String.valueOf(cell.getNumericCellValue());
}
break;
}
// 如果當前Cell的Type爲STRIN
case HSSFCell.CELL_TYPE_STRING:
// 取得當前的Cell字符串
cellvalue = cell.getRichStringCellValue().getString();
break;
// 默認的Cell值
default:
cellvalue = " ";
}
} else {
cellvalue = "";
}
return cellvalue;
}