上传excel文件

页面:



Upload File


  
   param0
  
   param1
 
   param name
 
   param name
 
   param name
 
   
  
     
 



后台:

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

你可能感兴趣的:(java,POI)