当前位置:网站首页>Apache poi 导入导出Excel文件
Apache poi 导入导出Excel文件
2022-06-12 06:19:00 【泠鸢9a】
引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
上传Excel
上传文件Dom
<div class="layui-body" style="margin: 1%">
<div class="layui-upload-drag" id="fileUpload">
<i class="layui-icon"></i>
<p>点击上传,或将文件拖拽到此处</p>
</div>
</div>
js
layui.use(['upload', 'element','table'], function() {
var $ = layui.jquery,upload = layui.upload,table = layui.table;
upload.render({
elem: '#fileUpload',
url: '/file/import',
accept:'file',
done: function(res){
console.log(res.msg);
}
});
}
Java代码
@RequestMapping("/import")
@ResponseBody
public ResponseResult importExcel(@RequestParam("file")MultipartFile file) throws Exception{
ResponseResult res=new ResponseResult();
// 1.文件不能为空
if (file.isEmpty()){
res.setMessage("文件为空,不能上传");
}
// 2.POI获取Excel解析数据
HSSFWorkbook wb=new HSSFWorkbook(file.getInputStream());
HSSFSheet sheet=wb.getSheetAt(0);
// 3.定义一个集合,接收文件中的数据
List<City> dataList=new ArrayList();
HSSFRow row=null;
// 4.解析数据,装到集合里面
for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
//定义实体
City data=new City();
//每一行的数据
row=sheet.getRow(i);
//解析数据
data.setCity(row.getCell(0).getStringCellValue());
data.setValue((int)row.getCell(1).getNumericCellValue());
dataList.add(data);
//3.插入数据库
cityService.addCity(dataList);
}
res.setCode("200");
res.setMessage("上传成功");
res.setObj(dataList);
return res;
}
导出Excel
导出Dom
<button type="button" class="layui-btn layui-btn-sm latui-btn-radius" lay-submit="" lay-filter="doExport">
<i class="layui-icon layui-icon-file">导出Excel</i>
</button>
js
form.on('submit(doExport)',function () {
window.location.href="/export"
})
Java代码
@RequestMapping("/export")
@ResponseBody
public void exportExcel(HttpServletResponse response) throws Exception {
//1.查询数据库,
List<City> datalist = cityService.findAll();
//2.建立Excel对象,封装数据
response.setCharacterEncoding("UTF-8");
//2.1 创建Excel对象
HSSFWorkbook wb=new HSSFWorkbook();
//2.2 创建sheet对象
HSSFSheet sheet = wb.createSheet("中国疫情数据Sheet1");
//2.3 创建表头
HSSFRow hssfRow=sheet.createRow(0);
hssfRow.createCell(0).setCellValue("城市名称");
hssfRow.createCell(1).setCellValue("确诊数量");
//3.遍历数据
for(City data:datalist){
HSSFRow dataRow=sheet.createRow(sheet.getLastRowNum()+1);
dataRow.createCell(0).setCellValue(data.getName());
dataRow.createCell(1).setCellValue(data.getValue());
}
//4.建立输出流,输出文件到浏览器
OutputStream os=null;
//4.1 设置Excel文件名称
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader( "Content-Disposition", "attachment;filename=" + new String( "疫情数据表".getBytes("gb2312"), "ISO8859-1" ));
//4.2 输出文件
os= response.getOutputStream();
wb.write(os);
os.flush();
//5.关闭输出流
os.close();
}
边栏推荐
- Zip and Items() difference
- Redis application (I) -- distributed lock
- zip 和.items()区别
- LeetCode-2034. Stock price fluctuation
- About why GPU early-z reduces overdraw
- Redis problem (I) -- cache penetration, breakdown, avalanche
- Houdini & UE4 programmed generation of mountains and multi vegetation scattering points
- 分段贝塞尔曲线
- (UE4 4.27) UE4 adds a customized meshpass to realize the edge illumination of the mobile terminal
- Redis data type (VII) -- hyperloglog
猜你喜欢

Video fire detection based on Gaussian mixture model and multi-color

BRDF of directx11 advanced tutorial PBR (2)

(UE4 4.27) UE4 adds a customized meshpass to realize the edge illumination of the mobile terminal

(UE4 4.27) add globalshder to the plug-in

SQL 注入读写文件

Pytorch implementation of regression model

Unity implements smooth interpolation

夜神模拟器adb查看log

Chartextcnn (Ag dataset - news topic classification)

Logistic regression model
随机推荐
Unity C script implements AES encryption and decryption
Qt-- realize TCP communication
Tips for using the potplayer video player
Understand Houdini's (heightfield) remap operation
Remap function of C different interval mapping
Redis queue
PHP 开发环境搭建及数据库增删改查
夜神模拟器adb查看log
Jetson TX2 machine brushing jetpack4.2 (self test successful version)
分段贝塞尔曲线
In unity3d, billboard effect can be realized towards another target
Textcnn (MR dataset - emotion classification)
Multithreading (2) -- pipeline (2) -- synchronized underlying monitor, lightweight, biased lock, lock inflation
PDF. js FAQs
Leetcode sword finger offer (Second Edition) complete version of personal questions
Redis data type (VII) -- hyperloglog
Leetcode personal question solution (Sword finger offer3-5) 3 Duplicate number in array, 4 Find in 2D array, 5 Replace spaces
Information content security experiment of Harbin Institute of Technology
Bert Chinese classification model training + reasoning + deployment
Redis configuration (IV) -- cluster