上传excel文件

页面:

<html>
<head>
<title>Upload File</title>
</head>
<body>
<form action="file/uploadExcel.json" method="post" enctype="multipart/form-data">  
   param0<input type="text" name="param"/> <br/>  
   param1<input type="text" name="param1"/> <br/> 
   param name<input type="text" name="param2"/> <br/> 
   param name<input type="text" name="param3"/> <br/> 
   param name<input type="text" name="param4"/> <br/> 
   <input type="file" name="file"/><br/>  
   <input type="submit" value="save"/>  
 </form>
</body>
</html>

后台:

jar包:spring-web-4.1.3.RELEASE.jar、poi-ooxml-3.9.jar、spring-context、poi-3.9.jar

package pyl.com.user;


import java.io.InputStream;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
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.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/file")
public class FileController {
/**
* 上传
* @param file
* @param map
* @throws Exception
*/
@RequestMapping("/uploadExcel")
public void uploadExcel(@RequestParam("file") MultipartFile file,
@RequestParam Map<String, String> map) throws Exception {
InputStream in = file.getInputStream();
Workbook wb = WorkbookFactory.create(in);
Sheet sheet = wb.getSheet("中文sheet");
int lastRowNum = sheet.getLastRowNum();
Row row = null;
Cell cell = null;
for (int i = 0; i < lastRowNum; i++) {
row = sheet.getRow(1);
short cellNum = row.getLastCellNum();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < cellNum; j++) {
cell = row.getCell(j);
String cellValue = getCellValue(cell);
sb.append(cellValue).append(",");
}
System.out.println("第" + (i + 1) + "行的数据是:" + sb.toString());
}
}
/**
* 获取cell的

* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
String strCell = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
strCell = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
// cell.getCellFormula();//获取公式字符串
try {// 获取计算后的值
strCell = cell.getNumericCellValue() + "";
} catch (Exception e) {
strCell = cell.getRichStringCellValue() + "";
}
break;
case Cell.CELL_TYPE_NUMERIC:
strCell = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
strCell = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK:
strCell = "";
break;
default:
strCell = "";
break;
}
}
if (strCell.equals("") || strCell == null) {
strCell = "";
}
return strCell.trim();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值