excel文件导出和导入
pom.xml添加依赖

@RestController
@RequestMapping(value = "/excel")
public class ExpImpExcelController { // 导出user表
@GetMapping(value = "/export/user")
public String getUser(HttpServletResponse response) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook();
// 给sheet起个名字
HSSFSheet sheet = workbook.createSheet("用户表"); // 创建表头
createTitle(workbook, sheet); // 准备数据,写入sheet
List<User> userList = new ArrayList<User>();
User user1 = new User("", "zhangsan1", "张三1", new Date());
User user2 = new User("", "zhangsan2", "张三1", new Date());
User user3 = new User("", "zhangsan3", "张三1", new Date());
userList.add(user1);
userList.add(user2);
userList.add(user3);
List<User> rows = userList;
// 设置日期格式
HSSFCellStyle style = workbook.createCellStyle();
HSSFDataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("yyyy年MM月dd日"));
// 新增数据行,并且设置单元格数据
int rowNum = ;
for (User user : rows) {
HSSFRow row = sheet.createRow(rowNum);
row.createCell().setCellValue(user.getId());
row.createCell().setCellValue(user.getUserName());
row.createCell().setCellValue(user.getNickName());
HSSFCell cell = row.createCell();
cell.setCellValue(user.getCreateTime());
cell.setCellStyle(style);
rowNum++;
} // 生成excel文件
String fileName = "用户表.xls";
buildExcelFile(fileName, workbook); // 浏览器下载excel
downloadExcelFile(fileName, workbook, response); return "";
} // 创建表头
private void createTitle(HSSFWorkbook workbook, HSSFSheet sheet) {
HSSFRow row = sheet.createRow();
// 设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
sheet.setColumnWidth(, * );
sheet.setColumnWidth(, * ); // 设置为居中加粗
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setFont(font); HSSFCell cell;
cell = row.createCell();
cell.setCellValue("ID");
cell.setCellStyle(style); cell = row.createCell();
cell.setCellValue("用户名");
cell.setCellStyle(style); cell = row.createCell();
cell.setCellValue("昵称");
cell.setCellStyle(style); cell = row.createCell();
cell.setCellValue("创建时间");
cell.setCellStyle(style);
} // 生成excel文件
protected void buildExcelFile(String filename, HSSFWorkbook workbook) throws Exception {
FileOutputStream fos = new FileOutputStream(filename);
workbook.write(fos);
fos.flush();
fos.close();
} // 浏览器下载excel
protected void downloadExcelFile(String filename, HSSFWorkbook workbook, HttpServletResponse response)
throws Exception {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} //导入excel
@PostMapping("/import/user")
public boolean addUser(@RequestParam("file") MultipartFile file) {
boolean a = false;
String fileName = file.getOriginalFilename();
try {
a = batchImport(fileName, file);
} catch (Exception e) {
e.printStackTrace();
}
return a;
} public boolean batchImport(String fileName, MultipartFile file) throws Exception {
Workbook wb = null;
try {
List<User> userList = new ArrayList<User>();
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
throw new RuntimeException("上传文件格式不正确");
}
boolean isExcel2003 = true;
if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
isExcel2003 = false;
}
InputStream is = file.getInputStream(); if (isExcel2003) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
Sheet sheet = wb.getSheetAt();
if (sheet == null) {
throw new RuntimeException("sheet页内容为空");
}
User user;
// 从第二行开始解析单元格
for (int r = ; r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
user = new User();
// excel 单元格类型
// CELL_TYPE_NUMERIC 数值型 0
// CELL_TYPE_STRING 字符串型 1
// CELL_TYPE_FORMULA 公式型 2
// CELL_TYPE_BLANK 空值 3
// CELL_TYPE_BOOLEAN 布尔型 4
// CELL_TYPE_ERROR 错误 5 if (row.getCell().getCellType() != Cell.CELL_TYPE_STRING) {
throw new RuntimeException("导入失败(第" + (r + ) + "行,ID请设为文本格式)");
}
String id = row.getCell().getStringCellValue();
if (id == null || id.isEmpty()) {
throw new RuntimeException("导入失败(第" + (r + ) + "行,ID未填写)");
} String userName = row.getCell().getStringCellValue();
if (userName == null || userName.isEmpty()) {
throw new RuntimeException("导入失败(第" + (r + ) + "行,用户名未填写)");
} String nickName = row.getCell().getStringCellValue();
if (nickName == null || nickName.isEmpty()) {
throw new RuntimeException("导入失败(第" + (r + ) + "行,昵称未填写)");
} Date createTime;
if (row.getCell().getCellType() != ) {
throw new RuntimeException("导入失败(第" + (r + ) + "行,创建日期格式不正确或未填写)");
} else {
createTime = row.getCell().getDateCellValue();
}
user.setId(id);
user.setUserName(userName);
user.setNickName(nickName);
user.setCreateTime(createTime);
userList.add(user);
}
} finally {
wb.close();
} return true;
}
}
public class User {
    private String id;
    private String userName;
    private String nickName;
    private Date createTime;
}
excel文件导出和导入的更多相关文章
- php excel文件导出之phpExcel扩展库
		
php Excel 文件导出 phpExcel 官网 http://phpexcel.codeplex.com/ /** * 导出特定文件 * 依据详细情况而定 */ public function ...
 - Excel接口导出,导入数据库(.Net)
		
public ActionResult TestExcel(string filePath) { return View(); } /// <summary> /// 根据Excel列类型 ...
 - SQL语句:把Excel文件中数据导入SQL数据库中的方法
		
1.从Excel文件中,导入数据到SQL数据库情况一.如果接受数据导入的表不存在 select * into jd$ from OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ...
 - loadrunner实现excel文件导出操作
		
项目中需要对“商品信息”进行查询及导出,但是loadrunner并不能录制到“保存”这一操作. 项目介绍:flex+Http协议: 不能录制的原因: 在我们点击了“导出”按钮后,服务端已经生成一份我们 ...
 - Ado.Net小练习01(数据库文件导出,导入)
		
数据库文件导出主要程序: <span style="font-family: Arial, Helvetica, sans-serif;"><span style ...
 - 使用npoi插件将excel文件导出
		
大致流程:前端使用URL地址的方式跳转到action后返回file类型数据 js: window.location.href = '/Home/index?Id=' + id 后台代码: /// &l ...
 - php excel文件导出之二 图像导出
		
PHP文件导出 之图像 和 文字同一时候导出 事实上之前写了个php文件导出.跟这个极为相似,由于项目须要对图像进行导出.查询一番.又写了一个, 这个能实现图像的导出(仅仅能是本地图像,不能使用远程图 ...
 - Jmeter_实现Excel文件导出到本地
		
一般而言,对于页面的“导出”操作,主要经历如下两个操作:①根据数据库的内容,将文件导出到应用服务器上:②将服务器上的文件下载到本地电脑: Jmeter同LoadRunner类似,只能记录服务端与客户端 ...
 - oracle dmp文件导出与导入
		
ORACLE 10g导入 ORACLE 11g 一.expdp.sh导出dmp文件export PATH=$PATH:$HOME/binexport ORACLE_BASE=/oracleexport ...
 
随机推荐
- 优化mybatis框架中的查询用户记录数的案例
			
通过对mybatis框架的中核心接口和类的分析,发现之前写的那个小demo是有问题的.现在对其进行部分优化. 如果存在多个功能的时候,势必会有很多重复的代码,如,创建sqlsession对象,关闭sq ...
 - fitnesse如何编辑用例
			
1.测试代码: 2.编写用例 (1)新建目录 点击“edit”,编辑内容: !1 测试 * '''[[算法][TestDemo]]''' * '''[[算法2][TestDemo2]]''' 上面的第 ...
 - [Algorithm] BFS vs DFS
			
//If you know a solution is not far from the root of the tree: BFS, because it is faster to get clos ...
 - (a2b_hex)binascii.Error: Non-hexadecimal digit found
			
HEX_CHAR = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] 错误:16进制字 ...
 - cube.js 学习(十一)cube + gitbase 分析git 代码
			
这个是一个简单的demo,使用gitbase+cube 分析git 仓库代码 需求 我们平时使用的gitlab,或者gogs 等git 仓库管理工具,有自己的管理强项,但是对于分析上可能就不是那么强大 ...
 - android 自己制作Jar包 和 修改 现成的 Jar包文件
			
先看如何创建自己的 Jar 包 里面随便写个方法 public int add(int a,int b){ return (a+b); } task makeJar(type: Copy) { del ...
 - c语言中一种典型的排列组合算法
			
c语言中的全排列算法和组合数算法在实际问题中应用非常之广,但算法有许许多多,而我个人认为方法不必记太多,最好只记熟一种即可,一招鲜亦可吃遍天 全排列: #include<stdio.h> ...
 - 洛谷 P2136 拉近距离 题解
			
P2136 拉近距离 题目背景 我是源点,你是终点.我们之间有负权环. --小明 题目描述 在小明和小红的生活中,有N个关键的节点.有M个事件,记为一个三元组(Si,Ti,Wi),表示从节点Si有一个 ...
 - sublime text 3 安装、添加命令行启动、汉化、注册码
			
1. 安装sublime: 下载:http://www.sublimetext.com/3 添加命令行启动:设置环境变量->计算机->右键属性->高级系统设置->环境变量-&g ...
 - Error:(1, 1) java: 非法字符: '\ufeff'
			
找到 java 文件. 使用 notepad 打开,转码,并保存即可.