1、数据库中的是mysql
2、需要导入poi的jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
<exclusions>
<exclusion>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
</exclusion>
</exclusions>
</dependency>
3、后台部分代码
@Controller
public class ImportEx {
@Autowired
private TbItemMapper tbItemMapper;
@RequestMapping("/partImprotdhh")
public TaotaoResult readXls() throws IOException {
//读取D盘下面的125.xls的excel文件
//这边的路径和文件名是写死的,可以试着根据用户自己选择的导入文件,写活
InputStream is = new FileInputStream("D:/125.xls");
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
TbItem tbItem = null;
List<TbItem> list = new ArrayList<TbItem>();
// 循环要导入的excel工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环遍历excel中的每一行
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
//获取excel中每行的记录
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
//封装实体类的对象
tbItem = new TbItem();
HSSFCell title = hssfRow.getCell(0);
HSSFCell sell_point = hssfRow.getCell(1);
HSSFCell price = hssfRow.getCell(2);
HSSFCell num = hssfRow.getCell(3);
HSSFCell barcode = hssfRow.getCell(4);
HSSFCell image = hssfRow.getCell(5);
HSSFCell cid = hssfRow.getCell(6);
HSSFCell status = hssfRow.getCell(7);
//IDUtils是获取ID的工具类
tbItem.setId(Long.valueOf(IDUtils.genItemId()));
tbItem.setTitle(getValue(title));
tbItem.setSellPoint(getValue(sell_point));
//从excel中读取出来的数字回自动加小数点和小数点后一位0的
//字符串
String pri=getValue(price);
int i=pri.indexOf(".");
String substring = pri.substring(0,i);
tbItem.setPrice(Long.valueOf(substring));
String nu=getValue(num);
int g=nu.indexOf(".");
String substring4 = nu.substring(0,g);
tbItem.setNum(Integer.valueOf(substring4));
tbItem.setBarcode(getValue(barcode));
tbItem.setImage(getValue(image));
String ci=getValue(cid);
int j=ci.indexOf(".");
String substring2 = ci.substring(0,j);
tbItem.setCid(Long.valueOf(substring2));
String sta=getValue(status);
int k=sta.indexOf(".");
String substring3 = sta.substring(0,k);
tbItem.setStatus(Byte.valueOf(substring3));
tbItem.setCreated(new Date());
tbItem.setUpdated(new Date());
list.add(tbItem);
}
}
}
int count=0;
for(int i=0;i<list.size();i++){
TbItem tbItem2=list.get(i);
count=tbItemMapper.insert(tbItem2);
}
if(count>0){
//TaotaoResult是自己封装的结果集
return TaotaoResult.ok();
}
return TaotaoResult.ok("失败");
}
@SuppressWarnings("static-access")
private String getValue(HSSFCell hssfCell) {
if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
// 返回布尔类型的值
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
// 返回数值类型的值
return String.valueOf(hssfCell.getNumericCellValue());
} else {
// 返回字符串类型的值
return String.valueOf(hssfCell.getStringCellValue());
}
}
}