这里写自定义目录标题
一、查看Excel表格
二、数据库中创建表
CREATE TABLE `hdsp_country_info` (
`ID` char(10) NOT NULL,
`code` char(6) DEFAULT NULL COMMENT '国家编码',
`name` varchar(20) DEFAULT NULL COMMENT '国家名称',
PRIMARY KEY (`ID`) USING BTREE,
UNIQUE KEY `pk_code` (`code`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
三、添加maven依赖
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId>
<version>1.0.6</version>
</dependency>
四、创建实体类
//lombok注解
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CountryCode {
/**
* id
*/
private String id;
/**
* 编码
*/
private String code;
/**
* 名称
*/
private String name;
}
五、dao层接口添加新增方法
@Mapper
@Repository
public interface BaseDao{
@Insert("insert into 表名 (ID,code,name) values (#{id},#{code},#{name})")
void insertCountry(CountryCode countryCode);
}
六、service层
1、service层接口
public interface IBaseService {
void insertCountry(CountryCode countryCode);
}
2、接口实现类
@Service
public class BaseServiceImpl implements IBaseService {
@Resource //注入dao层
private BaseDao baseDao;
@Override
public void insertCountry(CountryCode countryCode); {
return baseDao.insertCountry(countryCode);
}
}
七、controller层
@AutoWired
BaseServiceImpl baseService;
@Test
public void test(){
try{
jxl.Workbook wb =null;
//读取本地excel文件
InputStream in=new FileInputStream("excel文件路径");
wb = Workbook.getWorkbook(in);
Sheet sheet=wb.getSheet(0);
//获得excel数据总数量
int row_total = sheet.getRows();
for (int j=0;j<row_total;j++){
//获得当前行上的所有列上的数据数组
Cell[] cells=sheet.getRows(j);
//打印第j行第0列的数据
System.out.println(cells[0].getContents());
//打印第j行第1列的数据
System.out.println(cells[1].getContents());
CountryCode country=new CountryCode(String.valueOf(j),cells[0].getContents(),cells[1].getContents());
baseService.insertCountry(country);
}
}
catch(IOException e){
e.printStack();
}catch(BiffException e){
e.printStack();
}
}
需要注意的是,这个导出文件的后缀只支持xls